How to avoid flickering effect in angularjs - javascript

Can anybody help me how to fix this flicker effect when view is loading here is my code.
app.config(function($stateProvider,$urlRouterProvider,$routeProvider, $locationProvider,blockUIConfig) {
$urlRouterProvider.otherwise("/#");
$stateProvider
.state('dash', {
url: "/dash",
templateUrl: 'views/br_manager/pc_dashboard.html',
controller:'dashCtrl'
})
.state('pass', {
url: "/pass",
templateUrl: 'views/br_manager/change_password.html',
controller:'passwordCtrl'
})
.state('classroom', {
abstract:true,
url: "/classroom",
template: '<div ui-view style="height:100%"></div>',
controller:'classroomManagementCtrl'
})
.state('classroom.list', {
url: "",
templateUrl: 'views/br_manager/CR.html'
})
$locationProvider.html5Mode(true);
blockUIConfig.message = "Processing ...";
});
following is the code for controller and factory sevrvice
branchManager.factory('classroomFactory',function($resource,appConfig,$window){
var factory = {};
var fetch_classroom_url = appConfig.getMainAPI();
var authCode = $window.localStorage.getItem("authCode");
factory.fetchStandardList = function(selectedYear) {
return $resource(fetch_classroom_url+'/classroom/year/'+ selectedYear, {}, {
fetch : {
method : 'get',
isArray : false,
headers : { 'Authorization' : authCode },
interceptor : {
response : function(data) {
return data;
}
}
}
});
};
factory.fetchSectionList = function(currentStandard, selectedYear) {
return $resource(fetch_classroom_url+'/classroom/standard/'+ currentStandard +'/section/year/'
+ selectedYear, {}, {
fetch : {
method : 'get',
isArray : false,
headers : { 'Authorization' : authCode },
interceptor : {
response : function(data) {
return data;
}
}
}
});
};
return factory;
});
branchManager.controller('classroomManagementCtrl', function($scope,classroomFactory,appConfig,$state,$modal) {
var initials = {
syllabus:"",section:"",standard:"",year:"",classRoomId:"",maxcount:"",maxCount:""
};
$scope.year_list = ["2015-16","2016-17","2017-18","2018-19"];
$scope.fetchYearList = function(){
$scope.selectedYear = $scope.year_list[0];
$scope.fetchStandardList($scope.selectedYear);
};
$scope.fetchStandardList = function(selectedYear){
var year = window.btoa(selectedYear);
classroomFactory.fetchStandardList(year).fetch({},function(response){
$scope.standard_list =[];
if(response.status == 200 || response.status == 201){
if(response.data.standards != undefined){
var _data = angular.fromJson(response.data.standards);
$scope.standard_list = _data;
console.log( $scope.standard_list);
if($scope.standard_list.length > 0){
$scope.currentStandard = $scope.standard_list[0];
$scope.fetchSectionList($scope.currentStandard,selectedYear);
}else{
$scope.standard_list = ["-Nil-"];
}
}
}
},function(response){
$scope.standard_list = [];
$scope.currentStandard = "-Nil-";
$scope.response_msg = "There is no Standards found for this year.";
$scope.fetchSectionList($scope.currentStandard,selectedYear);
console.log(response.status);
});
};
$scope.fetchSectionList = function(currentStandard,selectedYear){
$scope.response_msg = "";
var standart = window.btoa(currentStandard);
var year = window.btoa(selectedYear);
classroomFactory.fetchSectionList(standart,year).fetch({},function(response){
$scope.classroom_list =[];
console.log(response);
if(response.status == 200 || response.status == 201){
if(response.data.classRoomLists!=undefined){
var _data = angular.fromJson(response.data.classRoomLists);
$scope.classroom_list = _data;
console.log( $scope.classroom_list);
$scope.$parent.setBaseContentHeight($scope.classroom_list.length);
}
}
},function(response){
$scope.classroom_list = [];
$scope.response_msg = "There is no classrooms found for this standard.";
$scope.$parent.setBaseContentHeight(-1);
console.log(response.status);
});
};
$scope.init = function(){
$scope.fetchYearList();
console.log("Init called")
};
$scope.cancel = function () {
$scope.response_msg = "";
$scope.response_msg1 = "";
$state.go('^.list');
};
$scope.init();
});
and my view looks like
<div class="col-lg-8 base-content table-base" style="height:90%;">
<div class="container-fluid" style="height: 90%;padding:0">
<div class="container-fluid" style="height: 30px;padding:0">
<div class="col-lg-2 col-md-2 col-sm-4 col-xs-4" style="font-size: medium;padding: 0 0 10px 0px" >
<a ui-sref="^.add"><button type="button" ng-click="addClassroom()" class="btn btn-color btn-sm">Add ClassRooms</button></a>
</div>
<div class="col-lg-3 col-md-3 col-sm-3 col-xs-3" style="padding: 0 0 20px 20px">
<select class="input-sm form-control" ng-model="selectedYear"ng-change="fetchStandardList(selectedYear)" ng-options="year as year for year in year_list" style="line-height: 1.5">
<option value="" selected="selected">-Year-</option>
</select>
</div>
<div class="col-lg-3 col-md-3 col-sm-3 col-xs-3" style="padding: 0 0 20px 20px">
<select class="input-sm form-control" ng-model="currentStandard" ng-change="fetchSectionList(currentStandard,selectedYear)" ng-options="currentStandard as currentStandard for currentStandard in standard_list" style="line-height: 1.5">
<option value="" selected="selected">-Class-</option>
</select>
</div>
<div class="col-lg-6 col-md-6 col-sm-12 col-xs-12 text-success response_msg" style="padding-top: 10px;" ng-hide="response_msg == undefined || response_msg == ''" >{{response_msg}}</div>
</div>
<div class="container-fluid" style="height:auto;padding:0;" ng-if="classroom_list== undefined || classroom_list.length <= 10">
<table class="table table-striped">
<thead>
<tr>
<th width="10%">Classroom Id</th>
<th width="10%">Year</th>
<th width="10%">Standard</th>
<th width="10%">Section</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="classroom in classroom_list">
<td width="10%">{{classroom.classRoomId}}</td>
<td width="10%">{{classroom.year}}</td>
<td width="10%">{{classroom.standard}}</td>
<td width="10%">{{classroom.section}}</td>
</tr>
</tbody>
</table>
<div ng-if="classroom_list.length == 0 || standard_list.length == 0" class="noData">No Classrooms Found</div>
<!-- <div ng-if="classroom_list == undefined " class="noData">Processing...</div>-->
</div>
<div class="container-fluid" style="padding:0" ng-if="classroom_list != undefined && classroom_list.length > 10">
<table class="table">
<thead>
<tr>
<tr>
<th width="10%">Classroom Id</th>
<th width="10%">Year</th>
<th width="10%">Standard</th>
<th width="10%">Section</th>
</tr>
</thead>
</table>
</div>
<div class="container-fluid slim-content" style="padding:0;" ng-if="classroom_list != undefined && classroom_list.length > 10" slim-scroll="{height:'88%',size:'3px',allowPageScroll :true,width:'100%'}">
<table class="table table-striped">
<tbody>
<tr ng-repeat="classroom in classroom_list">
<td width="10%">{{classroom.classRoomId}}</td>
<td width="10%">{{classroom.year}}</td>
<td width="10%">{{classroom.standard}}</td>
<td width="10%">{{classroom.section}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
any answers will be helpful thanks in advance.

Related

.replace() causing site to flicker

I am using mongoose-paginate-v2 on the backend to paginate the response from my DB. I am trying to setup the front end to move through the data and send a request for the new data as needed. (That part seems to be working). The problem I am having is the DOM seems to freak out after pressing the next / back buttons a few times. VIDEO of problem which is at the end of the 20sec vid: (https://drive.google.com/file/d/1btfeKqXELEMmBnFPpkCbBLY5uhrC1bvE/view?usp=sharing)
What I have tried: I have tried .emtpy, .remove, and now .replace all seem to have the same problem. I have also moved the code around to try and make it unti the prior .then() was complete. Here is the code:
Front End:
<% include ../partials/header%>
<div class="container-fluid pt-3">
<div class='row'>
<div class="col-md-1">
<button class="btn btn-outline-primary sticky-top">Start New Call</button>
</div>
<div class="col-md-11">
<table class="table">
<thead class="sticky-top">
<tr>
<th scope="col">Incident #</th>
<th scope="col">Type</th>
<th scope="col">Location</th>
<th scope="col">Units</th>
<th scope="col">Dispatch</th>
<th scope="col">Clear</th>
<th scope="col">Disposition</th>
<th scope="col">Recall</th>
</tr>
</thead>
<tbody id="callTable">
<tr id="row1"><td></td></tr>
<tr id="row2"><td></td></tr>
<tr id="row3"><td></td></tr>
<tr id="row4"><td></td></tr>
<tr id="row5"><td></td></tr>
<tr id="row6"><td></td></tr>
<tr id="row7"><td></td></tr>
<tr id="row8"><td></td></tr>
<tr id="row9"><td></td></tr>
<tr id="row10"><td></td></tr>
</tbody>
</table>
<div class="row">
<div class="col-3"></div>
<div class="text-center col-2">
<button id="back" class="btn btn-outline-success mr-auto"><i class="fas fa-step-backward"></i><strong>Back</strong></button>
</div>
<div class="justify-content-center d-flex col-2 align-items-center">
<strong>Page <span id="pgnum">##</span> of <span id="totalpgs">##</span></strong>
</div>
<div class="text-center col-2">
<button id="next" class="btn btn-outline-success ml-auto"><strong>Next</strong><i class="fas fa-step-forward"></i></button>
</div>
<div class="text-center col-3"></div>
</div>
</div>
</div>
</div>
<% include ../partials/footer %>
<script>
//Data Management Script
let list=[];
axios.get('/api/cnc/incidents')
.catch(err=>{
console.log(err);
})
.then(data=>{
return list=data;
})
//Setup Function to get data...
async function getPage(page){
axios.get('/api/cnc/incidents/'+page)
.catch(err=>{
console.log(err);
})
.then(response=>{
console.log(response);
calls = response.data.docs;
callNumber = 'Not Assigned';
next = response.data.hasNextPage,
back = response.data.hasPrevPage,
nextPage = response.data.nextPage,
prevPage = response.data.prevPage;
$('#pgnum').text(response.data.page);
$('#totalpgs').text(response.data.totalPages);
if(next === true){
$('#next').removeAttr('disabled');
$('#next').click(function () {
getPage(nextPage);
});
}else{
$('#next').attr('disabled', 'disabled');
}
if(back === true){
$('#back').removeAttr('disabled');
$('#back').click(function () {
getPage(prevPage);
});
}else{
$('#back').attr('disabled', 'disabled');
}
// activities.sort((a, b) => b.date - a.date)
calls.sort((a, b) => (a.times.dispatch > b.times.dispatch) ? -1 : 1)
return calls;
}).then(calls=>{
let i = 1;
calls.forEach(call => {
//Set default callNumber.
callNumber = 'Not Assigned'
//Update to call number from DB.
if(call.incidentNumber){
callNumber = call.incidentNumber;
}
//Change _id to Radio ID.
if(call.units.length > 0){
let assignedUnits = call.units;
let idArray = list.data[0];
const filtered = [];
function compare(assignedUnits,idArray){
assignedUnits.forEach((unit)=>{
idArray.forEach((unitId)=>{
if(unit === unitId._id){
filtered.push(unitId.id);
}
})
})
return filtered;
}
compare(assignedUnits, idArray);
callUnits = filtered.join(', ');
}else{
callUnits = ['None']
}
if(typeof call.disposition !== 'undefined'){
callDisposition = call.disposition.selected;
}else{
callDisposition = '';
}
if(call.times.clear === undefined){
callClear = '';
}else{
callClear = call.times.clear;
}
//Insert Data into DOM. and make TR the link to edit
$('#row'+i).replaceWith('<tr id="row'+i+'" onClick="editRun(\''+call._id+'\')"><th>'+callNumber+'</th><td>'+call.callType+'</td><td>'+call.address.placeName+' '+call.address.streetAddress+'</td><td>'+callUnits+'</td><td>'+call.times.dispatch+'</td><td>'+callClear+'</td><td>'+callDisposition+'</td><td id="recall">'+call.recall.length+' personnel</td></tr>');
i++;
});
})
}
//Get the first page of data...
getPage(1);
function editRun(runId){
window.location.href= '/api/cnc/incident/input/'+runId;
}
//Update Navbar correctly
$('document').ready(function(){
$('.top-nav').removeClass('active').addClass('text-light').removeClass('text-dark');
$('#incidentTab').addClass('active').addClass('text-dark').removeClass('text-light');
});
</script>

Knockout binding for array is not recognized

I am having an issue with my knockout not being recognized in html:
<div class="row-fluid">
<div class="span6">
<div class="control-group">
<fieldset>
<legend>Rates</legend>
<div id="creditcards-rates" class="row-fluid">
<p data-bind="visible: rates() == undefined || rates().length == 0">
No rates added yet.
</p>
<table data-bind="visible: rates() !== undefined && rates().length > 0" class="table table-striped table-condensed">
<thead>
<tr>
<th>Payment Status</th>
<th>Income Amount</th>
<th>Confirmed by Provider</th>
<th>Payment Status</th>
<th>Notes</th>
<th></th>
</tr>
</thead>
<tbody data-bind="foreach: rates">
<tr>
<td>
<input type="hidden" data-bind="value: Id, attr: { id: 'Rates[' + $index() + '].Id', name: 'Rates[' + $index() + '].Id' }" />
</td>
<td>
<a id="btn-remove" data-bind="click: $root.removeRate"><i class="icon icon-minus"></i></a>
</td>
</tr>
</tbody>
</table>
<button class="btn" data-bind="click: addNewRate"><i class="icon icon-plus"></i> Add New Payment</button>
</div>
</fieldset>
</div>
</div>
</div>
Problem is where data-bind doesn't recognize the values. I get error in console:
Error: Syntax error, unrecognized expression: input[data-bind='value:
Id, attr: { id: 'Rates[' + $index() + '].Id', name: 'Rates[' +
$index() + '].Id' }']
...);return a},bc.error=function(a){throw new Error("Syntax error,
unrecognized exp...
My knockout is:
var Micki = Micki || {};
Micki.Electro = {
Edit: function (options) {
var settings = $.extend({
id: 0
}, options);
var _alerts;
var _rates;
var vm;
function init(alerts, rates) {
_alerts = alerts;
_rates = rates;
vm = new ViewModel();
ko.applyBindings(vm);
function ViewModel(options) {
var self = this;
self.mediator = null;
self.publishKey = options.publishKey;
self.rates = ko.observableArray([]);
self.init = function (mediator, alerts, rates) {
self.mediator = mediator;
self.alerts = alerts;
//Rates.
$.each(rates, function (index, rate) {
var _rate = {
Id: ko.observable(rate.Id),
PaymentType: ko.observable(rate.PaymentType),
IncomeAmount: ko.observable(rate.IncomeAmount),
ConfirmedDate: ko.observable(rate.ConfirmedDate),
PaymentStatus: ko.observable(rate.PaymentStatus),
Note: ko.observable(rate.Note)
};
self.rates.push(_rate);
});
self.container.on("change keypress paste focus textInput input", function () {
self.mediator.publish(self.publishKey);
});
};
self.initFields = function () {
self.fields = [];
_.each($("[name^='Rates']"), function (field) {
self.fields.push(new Crate.Core.Field($(field), self.mediator, self.publishKey));
});
//_ratesAndTiers.initFields();
//_campaignSpecific.initFields();
};
self.addNewRate = function (data, event) {
alert("test");
};
return self;
}
}
}
}

pagination of my dataTable in angularJS

I have problem in pagination of my dataTable(angularJS),this is my code:
app.js:
.controller("StudentCtrl", ["$scope", "$http", "filterFilter", "$rootScope", "logger", "$filter", "$log", function($scope, $http, filterFilter, $rootScope, logger, $filter, $log) {
var init;
$scope.errors = [];
$scope.msgs = [];
$scope.filteredItems = [];
$scope.groupedItems = [];
$scope.itemsPerPage = 5;
$scope.pagedItems = [];
$scope.currentPage = 1;
$http({method: 'GET', url: 'myURL'})
.success(function(data){
$scope.posts = data; // response data
$scope.searchKeywords = "", $scope.filteredStores = [], $scope.row = "", $scope.select = function(page) {
var end, start;
return start = (page - 1) * $scope.numPerPage, end = start + $scope.numPerPage, $scope.currentPageStores = $scope.filteredStores.slice(start, end);
}, $scope.onFilterChange = function() {
return $scope.select(1), $scope.currentPage = 1, $scope.row = "";
}, $scope.onNumPerPageChange = function() {
//console.log("2");
return $scope.select(1), $scope.currentPage =1 ;
}, $scope.onOrderChange = function() {
return $scope.select(1), $scope.currentPage;
}, $scope.search = function() {
return $scope.filteredStores = $filter("filter")(data, $scope.searchKeywords), $scope.onFilterChange();
}, $scope.order = function(rowName) {
return $scope.row !== rowName ? ($scope.row = rowName, $scope.filteredStores = $filter("orderBy")(data, rowName), $scope.onOrderChange()) : void 0;
}, $scope.numPerPageOpt = [3, 5, 10, 20], $scope.numPerPage = $scope.numPerPageOpt[2], $scope.currentPage = 1, $scope.currentPageStores = [], (init = function() {
return $scope.search(), $scope.select($scope.currentPage);
})()
}).error(function(data, status, headers, config) {
});
students.html
<div class="page page-table" ng-controller="StudentCtrl">
<section class="table-dynamic">
<div class="bs-component" >
<div class="bs-example table-dynamic">
<div class="table-filters">
<div class="row">
<div class="col-sm-4 col-xs-6">
<form>
<input type="text"
placeholder="search"
class="form-control"
ng-model="searchKeywords"
ng-keyup="search()" style="border-radius: 20px;">
</form>
</div>
<div class="col-sm-3 col-xs-6 filter-result-info">
<span>
Showing {{filteredStores.length}}/{{posts.length}} entries
</span>
</div>
</div>
</div>
<table class="table table-bordered table-responsive table-hover">
<thead>
<tr>
<th >Nom</th>
<th >Prenom </th>
<th >DropOut </th>
<th >Live </th>
<th >Classe</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="post in posts">
<td align="center">{{post.LastName}}</td>
<td align="center">{{post.FirstName}}</td>
<td align="center">{{post.DropOut}}</td>
<td align="center">{{post.Live}}</td>
<td align="center">{{post.Class}}</td>
<footer class="table-footer">
<div class="row">
<div class="col-md-6 page-num-info">
<span>
Show
<select data-ng-model="numPerPage"
data-ng-options="num for num in numPerPageOpt"
data-ng-change="onNumPerPageChange()">
</select>
entries per page
</span>
</div>
<div class="col-md-6 text-right pagination-container">
<pagination class="pagination-sm"
page="currentPage"
total-items="filteredStores.length"
max-size="4"
on-select-page="select(page)"
items-per-page="numPerPage"
rotate="true"
boundary-links="true"
></pagination>
</div>
</div>
</footer>
</div></div></section></div>
this is what I get per example when I select 5 rows from all data(8 rows):
and this is when I clic on second page of paginator:(I get the 5 first items all the time not the rest of 8 rows)
so how can I set the informations in table rows from the paginator
thanks a lot for help
Update:jsfiddle code:
https://jsfiddle.net/1982ybj6/

keep track of each $timeout when calling the same function multiple times

$scope.fetchStatus = function (job) {
$http
.get('http://gtrapi/pool/checkStatus/' + sessionId + '/' + job.jobId)
.success(function (response) {
job[job.jobId] = response;
if (response.status !== 'InProgress') {
$scope.refreshDataTimeout = $timeout($scope.fetchStatus(job), 1000);
}
})
.error (function () {
});
};
Here is my HTML code
<div ng-repeat="job in gtrLogs" class="each-log">
<div class="row job-id">
<div class="col-xs-2">
Job ID: {{job.jobId}}
</div>
<div class="col-xs-10">
End Point: {{job.changes.endpoint}}
</div>
</div>
<div class="each-job" ng-init="fetchStatus(job)">
<div class="job-header row">
<span class="col-xs-6">Job Status: <strong>{{job[job.jobId].status}}</strong>
<span class="glyphicon" ng-class="{'glyphicon-refresh spin' : job[job.jobId].status === 'InProgress', 'glyphicon-ok' : job[job.jobId].status === 'submitted', 'glyphicon-remove' : job[job.jobId].status === 'Aborted'}"></span>
</span>
<span class="col-xs-6">
<span class="glyphicon glyphicon-stop pull-right" ng-click="stopLogs()" tooltip="Stop Action"></span>
<span class="glyphicon glyphicon-repeat pull-right" ng-click="rollBack()" tooltip="Roll Back"></span>
</span>
</div>
<div class="logs-progress">
<table class="table table-striped table-condensed table-hover">
<thead>
<tr>
<th>
Message
</th>
<th>
Time
</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="row in job[job.jobId].logs">
<td>{{row.msg}}</td>
<td>{{row.time | date:'yyyy/MM/dd HH:mm:ss'}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
I have to update the data every second and placed $timeout in the function. But because the function is being called multiple times from the HTML the calls are nested.
How Do I keep polling with respect to the same job.
Since you have a unique jobid, use can use that to maintain an array of key value pairs where your job id can correspond to a unique counter.
var counters = [];
$scope.fetchStatus = function (job) {
$http
.get('http://url:9090/gtrapi/pool/checkStatus/' + sessionId + '/' + job.jobId)
.success(function (response) {
job[job.jobId] = response;
if (response.status !== 'InProgress') {
updateCounter(job.jobId);
$scope.refreshDataTimeout = $timeout($scope.fetchStatus(job), 1000);
}
})
.error (function () {
});
};
function updateCounter(jobId) {
var exists = false,
jobId = parseInt(jobId);
for (var i in counters) {
if (counters[i].id === jobId) {
projects[i].counter++;
exists = true;
break;
}
}
if (!exists) {
counters.push({id: jobId, counter: 0});
}
}

How to modify and update data table row in angular js?

I m learning of angular js and i have found i issue .
I m creating a new projects .
i have some button edit , add, remove,
if i click to my edit button than show all field but i want to show only current field than i click to update update this filed .
My code is here
Anguar
var app = angular.module('addApp', []);
app.controller('modifyCtrl', ['$scope', function($scope){
$scope.tabelsData= [
{'name':'rohit', 'dob':'15-august-1985', 'emailId':'rohit#rohit.com', 'phone':'9999999999', 'address':'Delhi Rohini', 'id':'0' },
{'name':'aman', 'dob':'26-july-1975', 'emailId':'haryanat#hr.com', 'phone':'9874563210', 'address':'Haryana Sonepat', 'id':'1' },
{'name':'devraj', 'dob':'27-march-1980', 'emailId':'punjab#punjab.com', 'phone':'7410258963', 'address':'Punjab AmritSar', 'id':'2' }
];
$scope.modify = function(tableData){
$scope.modifyField = true;
$scope.viewField = true;
};
$scope.update = function(tableData){
$scope.modifyField = false;
$scope.viewField = false;
};
}]);
HTML Code is
<div ng-app="addApp">
<div class="wraper" ng-controller="modifyCtrl">
<table>
<thead>
<tr>
<th>Name:</th>
<th>Date Of Birth</th>
<th>Email Id</th>
<th>Phone No.</th>
<th>Address</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="tableData in tabelsData"><form>
<td>
<div ng-hide="viewField">{{tableData.name | uppercase}}</div>
<div ng-show="modifyField"><input type="text" ng-model="tableData.name" /></div>
</td>
<td>
<div ng-hide="viewField">{{tableData.dob}}</div>
<div ng-show="modifyField"><input type="text" ng-model="tableData.dob" /></div>
</td>
<td>
<div ng-hide="viewField">{{tableData.emailId}}</div>
<div ng-show="modifyField"><input type="text" ng-model="tableData.emailId" /></div>
</td>
<td>
<div ng-hide="viewField">{{tableData.phone}}</div>
<div ng-show="modifyField"><input type="text" ng-model="tableData.phone" /></div>
</td>
<td>
<div ng-hide="viewField">{{tableData.address}}</div>
<div ng-show="modifyField">
<textarea ng-model="tableData.address"></textarea>
</div>
</td>
<td>
<button ng-hide="viewField" ng-click="modify(tableData)">Modify</button>
<button ng-show="modifyField" ng-click="update(tableData)">Update</button>
<button ng-hide="viewField">Add</button>
<button ng-hide="viewField">Remove</button>
</td></form>
</tr>
</tbody>
</table>
</div>
</div>
var app = angular.module('addApp', []);
app.controller('modifyCtrl', ['$scope', function($scope){
$scope.tabelsData= [
{'name':'rohit', 'dob':'15-august-1985', 'emailId':'rohit#rohit.com', 'phone':'9999999999', 'address':'Delhi Rohini', 'id':'0' },
{'name':'aman', 'dob':'26-july-1975', 'emailId':'haryanat#hr.com', 'phone':'9874563210', 'address':'Haryana Sonepat', 'id':'1' },
{'name':'devraj', 'dob':'27-march-1980', 'emailId':'punjab#punjab.com', 'phone':'7410258963', 'address':'Punjab AmritSar', 'id':'2' }
];
$scope.modify = function(tableData){
$scope.modifyField = true;
$scope.viewField = true;
};
$scope.update = function(tableData){
$scope.modifyField = false;
$scope.viewField = false;
};
}]);
table td, table th{
border:solid 1px red;
padding:5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="addApp">
<div class="wraper" ng-controller="modifyCtrl">
<table>
<thead>
<tr>
<th>Name:</th>
<th>Date Of Birth</th>
<th>Email Id</th>
<th>Phone No.</th>
<th>Address</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="tableData in tabelsData"><form>
<td>
<div ng-hide="viewField">{{tableData.name | uppercase}}</div>
<div ng-show="modifyField"><input type="text" ng-model="tableData.name" /></div>
</td>
<td>
<div ng-hide="viewField">{{tableData.dob}}</div>
<div ng-show="modifyField"><input type="text" ng-model="tableData.dob" /></div>
</td>
<td>
<div ng-hide="viewField">{{tableData.emailId}}</div>
<div ng-show="modifyField"><input type="text" ng-model="tableData.emailId" /></div>
</td>
<td>
<div ng-hide="viewField">{{tableData.phone}}</div>
<div ng-show="modifyField"><input type="text" ng-model="tableData.phone" /></div>
</td>
<td>
<div ng-hide="viewField">{{tableData.address}}</div>
<div ng-show="modifyField">
<textarea ng-model="tableData.address"></textarea>
</div>
</td>
<td>
<button ng-hide="viewField" ng-click="modify(tableData)">Modify</button>
<button ng-show="modifyField" ng-click="update(tableData)">Update</button>
<button ng-hide="viewField">Add</button>
<button ng-hide="viewField">Remove</button>
</td></form>
</tr>
</tbody>
</table>
</div>
</div>
If you only want one row to show the inputs on clicking its respective modify button you have two options:
1) Attach booleans to each of the JSON indexes of the tabelsData array.
2) Make a mirror array that houses these booleans.
Having two separate booleans in this case is useless, because each one is being treated on a toggle basis:
Here is the core code for doing approach number two since I assume you want your data to remain the same:
JS:
$scope.editingData = {};
for (var i = 0, length = $scope.tabelsData.length; i < length; i++) {
$scope.editingData[$scope.tabelsData[i].id] = false;
}
$scope.modify = function(tableData){
$scope.editingData[tableData.id] = true;
};
$scope.update = function(tableData){
$scope.editingData[tableData.id] = false;
};
Html:
<tbody>
<tr ng-repeat="tableData in tabelsData">
<td>
<div ng-hide="editingData[tableData.id]">{{tableData.name | uppercase}}</div>
<div ng-show="editingData[tableData.id]"><input type="text" ng-model="tableData.name" /></div>
</td>
<td>
<div ng-hide="editingData[tableData.id]">{{tableData.dob}}</div>
<div ng-show="editingData[tableData.id]"><input type="text" ng-model="tableData.dob" /></div>
</td>
<td>
<div ng-hide="editingData[tableData.id]">{{tableData.emailId}}</div>
<div ng-show="editingData[tableData.id]"><input type="text" ng-model="tableData.emailId" /></div>
</td>
<td>
<div ng-hide="editingData[tableData.id]">{{tableData.phone}}</div>
<div ng-show="editingData[tableData.id]"><input type="text" ng-model="tableData.phone" /></div>
</td>
<td>
<div ng-hide="editingData[tableData.id]">{{tableData.address}}</div>
<div ng-show="editingData[tableData.id]">
<textarea ng-model="tableData.address"></textarea>
</div>
</td>
<td>
<button ng-hide="editingData[tableData.id]" ng-click="modify(tableData)">Modify</button>
<button ng-show="editingData[tableData.id]" ng-click="update(tableData)">Update</button>
<button ng-hide="viewField">Add</button>
<button ng-hide="viewField">Remove</button>
</td>
</tr>
</tbody>
I made an example:
http://plnkr.co/edit/lXq1WB
Here is an example in Angular2, (this will NOT work for AngularJS!)
fichier.html:
<ng2-toasty [position]="'top-left'"></ng2-toasty>
<label for="trainingInput" class="mr-2">{{ 'LABEL.FORMATION' | translate }} :</label>
<table class="table table-hover table-striped table-sortable table-bordered">
<thead>
<tr>
<th *ngFor="let column of columns" [class]="selectedClass(column.variable)" (click)="changeSorting(column.variable)" translate>
{{column.display}}
</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let object of data | orderBy : convertSorting(); let rowIndex = index">
<td *ngFor="let column of columns" class="{{column.variable}}-td">
<div *ngIf="!toUpdates[object['id']]" >{{object[column.variable] | format: column.filter}}</div>
<div *ngIf="toUpdates[object['id']]"><input type="text" [(ngModel)]="object[column.variable]" ></div>
</td>
<td class="text-center">
<i *ngIf="!toUpdates[object['id']]" class="fa fa-pencil-square-o edit-formation" aria-hidden="true" (click) = "editFormation(object)"></i>
<i *ngIf="toUpdates[object['id']]" class="fa fa-check-square-o save-edit-form" (click)="updateFormation(object)"></i>
<i class="fa fa-times" aria-hidden="true" (click)="deleteFormation(object['id'])"></i>
</td>
</tr>
<tr [hidden]="isDisabled()">
<td><input type="text" class="form-control" placeholder="Année" #years></td>
<td><input type="text" class="form-control" placeholder="Formation" #label></td>
<td><input type="text" class="form-control" placeholder="Durée" #duration></td>
<td class="text-center align-middle">
<i class="fa fa-plus-circle fa-2x" (click)="addFormation(years.value, label.value, duration.value)"></i>
</td>
</tr>
</tbody>
</table>
fichier.ts:
import {Component, Injector, Input, OnChanges, OnInit} from '#angular/core';
import { Http, Headers, RequestOptions, URLSearchParams } from '#angular/http';
import DynamicComponent from '../dynamic-component';
import Formation from './formation';
import {ToastyService, ToastyConfig, ToastOptions, ToastData} from 'ng2-toasty';
#Component({
moduleId: module.id,
selector: 'formations-selector',
templateUrl: './formations-template.html',
styleUrls: ['./formations-template.css'],
})
export default class FormationsComponent{
candidate: any = null;
listFormations: any = null;
candidateDetails: any = null;
columns: any[];
sort: any;
data: any[];
toUpdates: {};
constructor(private injector: Injector, private http: Http,private toastyService: ToastyService, private toastyConfig: ToastyConfig) {
this.candidateDetails = this.injector.get('candidateDetails');
this.candidate = this.candidateDetails.candidate;
this.listFormations = this.candidateDetails.listFormations;
this.columns = this.listFormations.columns;
this.sort = this.listFormations.sort;
this.data = this.listFormations.data;
this.toastyConfig.theme = 'material';
this.toUpdates = {};
}
ngAfterViewInit(){
$(document).ready(function() {
/*
$('.edit-formation').click(function () {
var dad = $(this).parent().parent();
dad.find('td .duration-span').hide();
dad.find('td.duration-td').append('<input type="text" class="form-control" placeholder="Durée" value="'+dad.find('td .duration-span').html()+'" id = "duration-update" #durationu>');
dad.find('td .label-span').hide();
dad.find('td.label-td').append('<input type="text" class="form-control" placeholder="Formation" id="label-update" value="'+dad.find('td .label-span').html()+'" #labelu>');
dad.find('td .years-span').hide();
dad.find('td.years-td').append('<input type="text" class="form-control" placeholder="Année" id="years-update" value="'+dad.find('td .years-span').html()+'" #yearsu>');
dad.find('td.years-td').append('<i class="fa fa-check-square-o save-edit-form hidden" (click)="updateFormation(1, years.value, label.value, durationu)"></i>');
dad.find('td .edit-formation').addClass("hidden");
dad.find('td .save-edit-form').removeClass("hidden");
});
*/
/*
$('.save-edit-form').click(function () {
var dad = $(this).parent().parent();
dad.find('td .save-edit-form').addClass("hidden");
dad.find('td .edit-formation ').removeClass("hidden");
dad.find('td .duration-span').show();
$('#duration-update').remove();
dad.find('td .label-span').show();
$('#label-update').remove();
dad.find('td .years-span').show();
$('#years-update').remove();
});
*/
});
}
//Action déclenché lors d'un changement de société du candidat : on met à jour la liste des métiers associés
onChangeCompaniesInput(value) {
}
isDisabled(isDisabled) {
//return (isDisabled || !this.candidateDetails.isUserAuthorized) ? true : false;
}
selectedClass(columnName): string{
return columnName == this.sort.column ? 'sort-' + this.sort.descending : '';
}
changeSorting(columnName): void{
var sort = this.sort;
if (sort.column == columnName) {
sort.descending = !sort.descending;
} else {
sort.column = columnName;
sort.descending = false;
}
}
convertSorting(): string{
return this.sort.descending ? '-' + this.sort.column : this.sort.column;
}
onChangeMainFormaion(value): void{
console.log(value);
}
deleteFormation(idFormation): void{
let headers = new Headers('Content-Type', 'application/json');
let params: URLSearchParams = new URLSearchParams();
this.http.post('/api/formations/'+idFormation+'/deleteFormation', params).toPromise()
.then(
res =>
{
if(res.status == 200){
this.toastyService.success({
title: "Success",
msg: "La formation a etait supprmié avec Succès",
showClose: true,
timeout: 5000,
theme: 'default',
});
}else{
this.toastyService.error({
title: "Error",
msg: "Une erreur est survenue, veuillez réessayer ultérieurement",
showClose: true,
timeout: 5000,
theme: 'default',
});
}
}
).catch(this.handleError);
}
editFormation(tableData): void{
this.toUpdates[tableData['id']]= true;
}
updateFormation(tableData): void {
this.toUpdates[tableData['id']]= false;
console.log(tableData);
}
addFormation(years: string, label: string, durration: string, main: boolean = false): void{
let headers = new Headers('Content-Type', 'application/json');
let params: URLSearchParams = new URLSearchParams();
params.append('years', years);
params.append('label', label);
params.append('durration', durration);
params.append('main', main);
//let formation = new Formation(years, label, durration, false);
return this.http.post('/api/formations/'+this.candidate.id+'/addFormation', params).toPromise()
.then(
res =>
{
if(res.status == 200){
this.toastyService.success({
title: "Success",
msg: "La formation a etait ajouter avec Succès",
showClose: true,
timeout: 5000,
theme: 'default',
});
}else{
this.toastyService.error({
title: "Error",
msg: "Une erreur est survenue, veuillez réessayer ultérieurement",
showClose: true,
timeout: 5000,
theme: 'default',
});
}
}
).catch(this.handleError);
}
private handleError(error: any) {
let errMsg = (error.message) ? error.message : error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg);
return Promise.reject(errMsg);
}
}

Categories