controller to populate the data into the datatable using angular js - javascript

I want to populate the data into the datatable but no data is getting populated into the table.
Error I'm getting on debugging is:
Uncaught TypeError: Cannot read property 'getContext' of null
html:
<table class="display table table-bordered table-striped" id="example">
<thead>
<tr>
<th>User Name</th>
<th>Email Id</th>
<th>Group Name</th>
<th>Created Date</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in items">
<td>{{item.user}}</td>
<td>{{item.email}}</td>
<td>{{item.groupName}}</td>
<td>{{item.createdAt}}</td>
</tr>
</tbody>
</table>
controller:
(function () {
"use strict";
angular.module('app').controller('superAdminController', function ($scope, AuthenticationService, $timeout, $location, $http, myConfig) {
AuthenticationService.loadSuperAdmin(function (response) {
if (response.data.success) {
$scope.populateTable(response.data);
console.log(response.data);
} else {
$scope.items = [];
}
});
$scope.populateTable = function (data) {
$scope.items = data.loadSuperAdminData;
$timeout(function () {
$("#example").dataTable();
}, 200)
};
});
}());

In controller, you can populate your server response like this.
$.post(MY_CONSTANT.url + '/api_name',{
access_token: accessToken
}).then(
function(data) {
var dataArray = [];
data = JSON.parse(data);
var lst = data.list;
lst.forEach(function (column){
var d = {user: "", email: "", group: "", created: ""};
d.user = column.user;
d.email = column.email;
d.groupName = column.group;
d.createdAt = column.created;
dataArray.push(d);
});
$scope.$apply(function () {
$scope.list = dataArray;
// Define global instance we'll use to destroy later
var dtInstance;
$timeout(function () {
if (!$.fn.dataTable) return;
dtInstance = $('#datatable4').dataTable({
'paging': true, // Table pagination
'ordering': true, // Column ordering
'info': true, // Bottom left status text
// Text translation options
// Note the required keywords between underscores (e.g _MENU_)
oLanguage: {
sSearch: 'Search all columns:',
sLengthMenu: '_MENU_ records per page',
info: 'Showing page _PAGE_ of _PAGES_',
zeroRecords: 'Nothing found - sorry',
infoEmpty: 'No records available',
infoFiltered: '(filtered from _MAX_ total records)'
}
});
var inputSearchClass = 'datatable_input_col_search';
var columnInputs = $('tfoot .' + inputSearchClass);
// On input keyup trigger filtering
columnInputs
.keyup(function () {
dtInstance.fnFilter(this.value, columnInputs.index(this));
});
});
// When scope is destroyed we unload all DT instances
// Also ColVis requires special attention since it attaches
// elements to body and will not be removed after unload DT
$scope.$on('$destroy', function () {
dtInstance.fnDestroy();
$('[class*=ColVis]').remove();
});
});
});

Related

How to get object of array in view file in ionic framework

I am working with ionic framework I am getting data into localStorage.
.controller('AppCtrl', function(Auth,$scope,$http, $ionicModal,$location,$state,$window,$localStorage, $sessionStorage,$timeout,$ionicSideMenuDelegate) {
//$scope.$on('$ionicView.leave', function () { $ionicSideMenuDelegate.canDragContent(true) });
$scope.adminData = $localStorage.adminData;
$scope.forgetData = $sessionStorage.forgetData;
$scope.levels = $localStorage.levels;
$scope.loginData = {}
// Create the login modal that we will use later
$ionicModal.fromTemplateUrl('templates/login.html', {
scope: $scope
}).then(function(modal) {
$scope.modal = modal;
});
$scope.levels = function() {
$http({
url: 'http://localhost/bearscoaching/api/classes',
headers : {
'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'}
})
.then(function successCallback(response)
{
function isObjectHasData(object)
{
return (object != null && typeof object != 'undefined' && Object.keys(object).length > 0);
}
if(isObjectHasData(response.data))
{
$scope.dp = response.data;
$localStorage.levels = $scope.dp;
/*angular.forEach($localStorage.levels, function(user, arrayID)
{
alert(user.name);
});*/
$state.go('app.search');
}
else
{
alert("Data is not available");
//$state.go('app.dashboard');
}
}, function errorCallback(response)
{
console.log(response);
// $state.go('app.dashboard');
alert("Data is not available");
});
};
})
when I run foreach loop I am getting every name in alert.But when I get these data in view file like:
<ion-modal-view>
<ion-view view-title="Marie Simpson" id="mainpage" hide-nav-bar="false">
<ion-content padding="true" scroll="false">
<table>
<thead>
<th>Name</th>
</thead>
<tbody ng-repeat="item in levels">
<tr>
<td>{{item.name}}</td>
</tr>
</tbody>
</table>
</ion-content>
</ion-view>
</ion-modal-view>
I am not getting name of list.my response is
ngStorage-levels: "[{"id":2,"name":"Level I"},{"id":3,"name":"Level I…":6,"name":"Level V"},{"id":7,"name":"Level VI"}]"

ngTable with server side loading doen't update

I'm using ngTable to display a large table with data coming from the server. The initial data is displayed correctly. When I try sorting by a column or try going to the next page there is a request and correct response being sent and received, the getData function resolves it but the table isn't being updated in any way. It just shows the first page with the initial data.
HTML:
<table class="table table-bordered" ng-table-dynamic="table.detailsParams with table.cols" >
<tr ng-repeat="row in $data track by $index">
<td ng-repeat="col in $columns">{{::row[col.field]}}</td>
</tr>
</table>
JS:
scope.$on('campaign-changed', function (event, args) {
scope.campaign = args.campaign;
scope.campaign.createdAt = moment(scope.campaign.createdAt).format('DD MMM, YYYY')
scope.table.detailsParams = new NgTableParams({
count: 10,
sorting: { campaignName: "desc" }
}, {
getData: function (params) {
// ajax request to api
if (typeof params.total() == 'undefined' || params.total() == 0) {
ajaxSrv.getDetailsTotalCount(scope.campaign.id, function (data) {
params.total(data.data[0]);
})
}
var req = ajaxSrv.getCampaignData(params.url(), scope.campaign.id).then(function (response) {
return $q.resolve(response.data.data);
})
return $q.resolve(req);
}
});
})

Angular Table Refresh

I have an api that gets called on page load. The data from the api is loaded into a table via angular ng-repeat. I also have a javascript function that gets called every 10 seconds that calls the same api for the same dataset. I Would like to know how i can apply the new dataset to the table and replace the old if the dataset changes and how to visually show this change with animation. The code is below.
Table code
<body ng-app="myApp" ng-controller="ScansController">
<div class="bs-example" id="scan-table">
<table id="scansTable" class="table table-striped">
<thead>
<tr>
<th>ScanId</th>
<th>First Name</th>
<th>Last Name</th>
<th>Time Stamp</th>
</tr>
<tr ng-repeat="scan in Scans">
<td>
{{scan.scanId}}
</td>
<td>
{{scan.firstName}}
</td>
<td>
{{scan.lastName}}
</td>
<td>
{{scan.timeStamp}}
</td>
</tr>
</thead>
</table>
</div>
Javascipt interval code
<script>
window.setInterval(function () {
$.ajax({
url: 'api/scans/',
type: 'Get',
dataType: 'json',
success: function (data) {
//Something here
},
error: function () {
alert("something failed");
}
});
}, 10000);
</script>
Angular Code
var myApp = angular.module('myApp', []);
myApp.service('dataService', function ($http) {
this.getData = function () {
return $http({
method: 'GET',
url: '/api/scans/'
});
}
});
myApp.controller('ScansController', function ($scope, dataService) {
$scope.Scans = [];
dataService.getData().then(function (result) {
$scope.Scans = result.data;
console.log(result.data);
});
});
You need to stay inside the current scope.
Setting an interval on a $http call is poison. Use a $timeout inside the success callback to recursively call the next interval.
myApp.controller('ScansController', function ($scope, $timeout, dataService) {
$scope.Scans = [];
function fetchData(){
dataService.getData().then(function (result) {
$scope.Scans = result.data;
$timeout(function(){ fetchData(); },10000);
});
}
fetchData();
});
As far as the table refresh that didnt get addressed, this is how i was able to make it work. I downloaded and applied the animate.css. I then gave the table a starting class to animate it on class load. I then have a function that fetches the array of data on page load and then another that fetches every .5 seconds and compares. If anything has changed, then the class is reapplied and it shows animation.
Angular Ng-Repeat Table
<link href="~/Content/animate.min.css" rel="stylesheet" />
<h1>
Scans
</h1>
<body ng-app="myApp" ng-controller="ScansController" >
<table id="scansTable" class="table table-striped">
<thead>
<tr>
<th>ScanId</th>
<th>First Name</th>
<th>Last Name</th>
<th>Time Stamp</th>
</tr>
<tr ng-repeat="scan in Scans" ng-class-odd="'odd'" ng-class-even="'even'" class="animated bounceIn">
<td>
{{scan.scanId}}
</td>
<td>
{{scan.firstName}}
</td>
<td>
{{scan.lastName}}
</td>
<td>
{{scan.timeStamp}}
</td>
</tr>
</thead>
</table>
Angular Controller
var myApp = angular.module('myApp', []);
myApp.service('dataService', function ($http) {
this.getData = function () {
return $http({
method: 'GET',
url: '/api/scans/'
});
}
});
myApp.controller('ScansController', function ($scope, dataService, $timeout) {
$scope.Scans = [];
$scope.NewScans = [];
function fetchData() {
dataService.getData().then(function (result) {
$scope.Scans = result.data;
$("#scansTable").removeClass('animated bounceIn');
});
}
function fetchNewData() {
dataService.getData().then(function (result) {
$scope.NewScans = result.data;
if ($scope.Scans.length != $scope.NewScans.length)
{
$("#scansTable").addClass('animated bounceIn');
$scope.Scans = $scope.NewScans
}
$timeout(function () { fetchNewData(); }, 500);
});
}
fetchData();
fetchNewData();
});

AngularJS: ng-repeat table doesn't update from UIB Modal

I have looked at a number of other questions related to this such as
AngularJS : ng-repeat list is not updated when a model element is spliced from the model array
ng-repeat not updating on update of array
However I think that the way I built my app is sufficiently different that these aren't helping me.
I think my idea of doing this:
$rootScope.$on('connectionDispositionChanged',function(event, item){
$scope.data.matches[item.index].info.disposition = item.disposition;
});
Isn't really working out the way I had hoped. I can actually see in the console that this updating, but it doesn't update in the table. Adding $scope.$apply() after this causes a digest in-progress error.
show.phtml
<div class="container-fluid" ng-app="analysisApp" ng-controller="analysisController">
<table class="table table-condensed">
<thead>
<tr >
<th ng-repeat="header in baseColumns" class="text-center">{{header.name | tableHeader}}</th>
<th ng-repeat="header in comparisonColumns" class="text-center text-info">{{header.name | tableHeader}}</th>
<th> </th>
</tr>
</thead>
<tbody>
<tr table-row data="data" ng-repeat="item in data.matches | filter:searchMatchText track by $index">
</tbody>
</table>
<row class="col-md-12 text-center"><span class="text-muted">End of Data</span></row>
</div><!-- #matches -->
</div>
tableRowDirective.js
"use strict";
analysisApp.directive("tableRow", function($compile) {
var getTemplate = function(scope, element, attrs){
var base = scope.item.base;
var comp = scope.item.comparison;
var info = scope.item.info;
// other non-relevant code...
returnString += '<td class="text-center"><button class="btn btn-default btn-xs" ng-click="matchesSetDisposition(item, data.settings, $index)" >Set Disposition</button>';
returnString += '</td>';
return returnString;
};
var linker = function(scope, element, attrs){
element.html(getTemplate(scope, element, attrs));
$compile(element.contents())(scope);
};
return {
restrict : "A",
replace : true,
link: linker
};
});
analysisController.js
"use strict";
analysisApp.controller('analysisController', ['$scope','$rootScope','loadData','saveData','$uibModal', function ($scope, $rootScope, loadData, saveData, $uibModal, $log) {
$rootScope.$on('connectionDispositionChanged',function(event, item){
// $scope.data.matches[item.index].info.disposition = item.disposition;
});
$scope.matchesSetDisposition = function(item, scope, index){
var modalInstance = $uibModal.open({
animation: $scope.animationsEnabled,
templateUrl: '/angular/analysis/templates/matches-modal.html',
controller: 'matchesModalController',
size: 'lg',
resolve: {
itemData: function () {
return {
dispositionLabels: $scope.dispositionLabels,
disposition: item.info.disposition,
connectionID: item.info.id,
comparisonID: comparisonID,
baseItemID: item.base.id,
baseTitle: itemTitle(item.base),
comparisonItemID: item.comparison.id,
comparisonTitle: itemTitle(item.comparison),
index: index
}
}
}
});
modalInstance.result.then(function (item) {
$scope.data.matches[item.index].info.disposition = item.disposition;
saveTheData('/analysis/apisaveconnectiondisposition', item);
}, function () {
});
};
}]);
matchesModalController.js
"use strict";
analysisApp.controller('matchesModalController', function ($scope, $rootScope, $uibModalInstance, itemData, saveData) {
$scope.itemData = itemData;
$scope.ok = function (item) {
$uibModalInstance.close(item);
};
$scope.cancel = function () {
$uibModalInstance.dismiss('cancel');
};
$scope.delink = function (item) {
BootstrapDialog.confirm({
title: 'WARNING',
message: '<p>Are you sure that you want to break the link between these items?</p>',
type: BootstrapDialog.TYPE_DANGER,
btnOKLabel: 'Break the link',
btnOKClass: 'btn-danger',
callback: function(result) {
if(result) {
$uibModalInstance.dismiss('delink');
saveTheData('/analysis/apidelink', item);
}else {
// cancel the operation
}
}
});
};
var saveTheData = function(url, item){
saveData
.postData(url, item)
.then(function(dataResponse){
$rootScope.$broadcast('connectionDispositionChanged', item);
})
};
});

ASP.NET MVC 6 Angular JS Table Update

I'm currently learning new MVC 6 and stucked completely with simple action - table data update on item selection change.The desired behaviour is to load questions that belong selected question block
I have angularJS factory:
(function () {
'use strict';
angular
.module('questionBlockApp')
.factory('questionBlockService', questionBlockService);
var questionBlockService = angular.module('questionBlockService', ['ngResource']);
questionBlockService.factory('Blocks', ['$resource',
function ($resource) {
return $resource('/api/blocks/', {}, {
query: { method: 'GET', params: {}, isArray: true }
});
}]);
questionBlockService.factory('Questions', ['$resource',
function ($resource) {
return $resource('/api/blocks/:blockId', {blockId : '#blockId'}, {
query: { method: 'GET', params: {}, isArray: true }
});
}]);
})();
Controller, which has refresh func (loadQuestions) built inside selection change function:
(function () {
'use strict';
angular
.module('questionBlockApp')
.controller('questionBlockController', questionBlockController);
//.controller('questionController', questionController);
questionBlockController.$inject = ['$scope', 'Blocks', 'Questions'];
//questionController.$inject = ['$scope', 'Questions'];
function questionBlockController($scope, Blocks, Questions) {
$scope.selectedBlock = 2;
if ($scope.Blocks == undefined | $scope.Blocks == null) {
$scope.Blocks = Blocks.query();
}
$scope.setSelected = function (blockId) {
$scope.selectedBlock = blockId;
$scope.loadQuestions();
}
$scope.loadQuestions = function () {
$scope.data = Questions.query({ blockId: $scope.selectedBlock });
$scope.data.$promise.then(function (data) {
$scope.Questions = data;
});
};
$scope.loadQuestions();
}
})();
And views:
View from which setSelected is called:
<table class="table table-striped table-condensed" ng-cloak ng-controller="questionBlockController">
<thead>
...
</thead>
<tbody>
<tr ng-repeat="block in Blocks" ng-click="setSelected(block.Id)" ng-class="{'selected': block.Id == selectedBlock}">
<td>{{block.Id}}</td>
<td>{{block.Name}}</td>
<td>{{block.Created}}</td>
</tr>
</tbody>
</table>
<table id="test" ng-controller="questionBlockController">
<thead>
<tr>
...
</tr>
</thead>
<tbody>
<tr ng-repeat="question in Questions">
<td>{{question.Id}}</td>
<td>{{question.Text}}</td>
<td>{{question.TimeLimit}}</td>
<td>{{question.Updated}}</td>
</tr>
</tbody>
</table>
When I click on different items in QuestionBlock table, $scope.Questions is updated properly, but the table does not reflect changes, as if no binding exists.
Okay, I am just a bit damaged.
There are two questionBlockController controllers defined, leading to intialization of different scopes => two $scope.Questions objects existence => refresh occured in Blocks scope, which was undesired behaviour.

Categories