How to add pagination using angular js in datatable - angularjs

**How to add pagination using angular js in jquery Datatable plugin. There is some external plugin available like angular js data table that directly allows pagination but i want to make inside jquery data table. **
var app= angular.module("myModule",['ui-bootstrap']);
app.controller("dataController",function($scope,$http){
$http({
method: 'GET',
url: 'https://api.myjson.com/bins/833qv'
}).then(function successCallback(response) {
$scope.employees=response.data;
console.log($scope.employees);
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<title>Angula js | Home </title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1" />
</head>
<body>
<div ng-app="myModule">
<input type="text" ng-model="searchFilter" />
<div ng-controller="dataController">
<table style="width:500px;border:2px solid black;">
<thead>
<tr style="text-align:left;">
<th>Id</th>
<th>Client name</th>
<th>Client code</th>
<th>Team id</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="employee in employees">
<td>{{employee.id}}</td>
<td>{{employee.client_name}}</td>
<td>{{employee.client_code}}</td>
<td>{{employee.team_id}}</td>
</tr>
</tbody>
</table>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.5/angular.min.js"></script>
<script src="custom.js"></script>
</body>
</html>
its not accepting datatable pagination. can it possible that angular js accept datatable jqyery pagination.

Pagination:
HTML part
<ul>
<li class="paginationclass" style="font-weight:bold;"><span>Name</span><span>Age</span><span>Designation</span></li>
<li class="paginationclass" ng-repeat="datalist in datalists | pagination: curPage * pageSize | limitTo: pageSize">
<div><span>{{ datalist.name }} </span><span>{{ datalist.age }}</span><span>{{ datalist.designation }}</span></div>
</li>
</ul>
<div class="pagination pagination-centered" ng-show="datalists.length">
<ul class="pagination-controle pagination">
<li>
<button type="button" class="btn btn-primary" ng-disabled="curPage == 0"
ng-click="curPage=curPage-1"> < PREV</button>
</li>
<li>
<span>Page {{curPage + 1}} of {{ numberOfPages() }}</span>
</li>
<li>
<button type="button" class="btn btn-primary"
ng-disabled="curPage >= datalists.length/pageSize - 1"
ng-click="curPage = curPage+1">NEXT ></button>
</li>
</ul>
</div>
</div>
</div>
JS part
var myapp = angular.module('sampleapp', [ ]);
myapp.controller('samplecontoller', function ($scope) {
$scope.showData = function( ){
$scope.curPage = 0;
$scope.pageSize = 3;
$scope.datalists = [
{ "name": "John","age":"16","designation":"Software Engineer1"},
{"name": "John2","age":"21","designation":"Software Engineer2"},
{"name": "John3","age":"19","designation":"Software Engineer3"},
{"name": "John4","age":"17","designation":"Software Engineer4"},
{"name": "John5","age":"21","designation":"Software Engineer5"},
{"name": "John6","age":"31","designation":"Software Engineer6"},
{"name": "John7","age":"41","designation":"Software Engineer7"},
{"name": "John8","age":"16","designation":"Software Engineer8"},
{"name": "John18","age":"16","designation":"Software Engineer9"},
{"name": "John28","age":"16","designation":"Software Engineer10"},
{"name": "John38","age":"16","designation":"Software Engineer11"},
{"name": "John48","age":"16","designation":"Software Engineer12"},
{"name": "John58","age":"16","designation":"Software Engineer13"},
{"name": "John68","age":"16","designation":"Software Engineer14"},
{"name": "John68","age":"16","designation":"Software Engineer15"}
]
$scope.numberOfPages = function() {
return Math.ceil($scope.datalists.length / $scope.pageSize);
};
}
});
angular.module('sampleapp').filter('pagination', function()
{
return function(input, start)
{
start = +start;
return input.slice(start);
};
});

Use this open source library basically enhanced version of JQuery DataTables to rendered tables which include pagination, sorting, searching and filtering and very good support of accessibility.
https://assets.cms.gov/resources/framework/2.0/Pages/datatables.html.

Related

Stop event propogation from DOM elements created dynamically via a library

I'm using AngularJS 1.7.5, x-editable, and smart table. Inside of a table row I have an anchor which opens a select via x-editable. I am also enabling row selection in smart table.
The problem is that I am unsure of how to stop the click event from the select from propogating and selecting or deselecting the table row. I have written a directive to suppress the click from the A element which opens the select, but the select is created by the x-editable library (e.g. not in my HTML.)
https://plnkr.co/edit/kAKbgLg05uBA9etICxV7?p=preview
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script data-require="jquery#*" data-semver="3.2.1" src="https://cdn.jsdelivr.net/npm/jquery#3.2.1/dist/jquery.min.js"></script>
<script data-require="angular.js#1.7.0" data-semver="1.7.0" src="https://code.angularjs.org/1.7.0/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-smart-table/2.1.8/smart-table.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/1.1.2/ui-bootstrap-tpls.js"></script>
<script data-require="xeditable#*" data-semver="0.1.8" src="https://vitalets.github.io/angular-xeditable/dist/js/xeditable.js"></script>
<link data-require="bootstrap-css#3.3.7" data-semver="3.2.0" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" />
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-controller="myController as $ctrl">
<table st-table="collection" class="table">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Secret Identity</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="row in collection" st-select-row="row" st-select-mode="multiple">
<td>{{ row.id }}</td>
<td>{{ row.name }}</td>
<td>
<a href="#" editable-select="row.secretIdentity" data-value="{{ row.secretIdentity }}" class="editable editable-click" buttons="no" mode="inline" e-ng-options="i for i in options" stop-event="click">
{{ row.secretIdentity }}
</a>
</td>
</tr>
</tbody>
</table>
</body>
</html>
angular
.module('myApp', ['xeditable', 'smart-table', 'ui.bootstrap'])
.controller('myController', ['$scope', 'editableOptions', function($scope, editableOptions) {
editableOptions.theme = 'bs3';
$scope.collection = [{
name: 'Ed',
id: 1,
secretIdentity: 'Just some guy'
}, {
name: 'Tony',
id: 2,
secretIdentity: 'Iron Man'
}, {
name: 'Steve',
id: 3,
secretIdentity: 'Captain America'
}, {
name: 'Bruce',
id: 4,
secretIdentity: 'Hulk'
}, {
name: 'Clint',
id: 5,
secretIdentity: 'Hawkeye'
}, {
name: 'Natasha',
id: 6,
secretIdentity: 'Black Widow'
}, ];
$scope.options = ['Iron Man', 'Captain America', 'Hulk', 'Black Widow', 'Hawkeye', 'Just some guy'];
}])
.directive('stopEvent', () => {
return {
restrict: 'A',
link: (scope, element, attr) => {
if (attr && attr.stopEvent) {
element.bind(attr.stopEvent, e => {
e.stopPropagation();
});
}
}
};
});
Is there a standard way for manipulating elements created by x-editable which will also play nice with AngularJS?
You can wrap your <a> in a <div> and add your stop-event directive to that div.
<td>
<div stop-event="click">
<a href="#"
editable-select="row.secretIdentity"
data-value="{{ row.secretIdentity }}"
class="editable editable-click"
buttons="no"
mode="inline"
e-ng-options="i for i in options"
>
{{ row.secretIdentity }}
</a>
</div>
</td>

angular, select with dynamic disabled

Now I am trying to select box with disabled.
When $shop.products.product[i].productId is changed by selectBox, I want that value disabled in select box option.
for example, if i select 3 in select box on second row, then select box option 1,3 are disabled.
so i register $watch witch resync isDisabled field when $shop.products[i].productId is changed.
i don't know why $watch is no calling. help me please.
// Code goes here
angular.module("myApp")
.controller("myCtrl", function($scope) {
$scope.shop = {
"id" : 'shop1',
"products" : [
{"productId" : 1,"desc" : 'product1'},
{"productId" : 2,"desc" : 'product2'}
]
};
$scope.allSelectBoxItems = [
{"id" : 1, "isDisabled" : true},
{"id" : 2, "isDisabled" : true},
{"id" : 3, "isDisabled" : false},
{"id" : 4, "isDisabled" : false}
];
$scope.addWatcher = function(index){
console.log('register watcher to ' + index);
$scope.$watch('shop.product[' + index + '].productId', function(newValue, oldValue){
console.log('watcher envoked');
if (newValue != oldValue) {
var selected = $scope.shop.products.map(function (product) {
return product.productId;
});
for (var i = 0; i < $scope.allSelectBoxItems.length; i++) {
var isSelected = selected.includes($scope.allSelectBoxItems[i].productId);
console.log(isSelected);
$scope.allSelectBoxItems.isDisabled = isSelected;
}
}
});
}
angular.forEach($scope.shop.products, function(value, index){
$scope.addWatcher(index);
});
$scope.addProduct = function(){
var nextProductId = $scope.shop.products.length + 1;
var newProduct = {"productId" : nextProductId ,"desc" : 'product' + nextProductId};
$scope.shop.products.push(newProduct);
$scope.addWatcher(nextProductId - 1);
}
});
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://code.angularjs.org/1.6.4/angular.min.js"></script>
<script src="https://code.angularjs.org/1.6.4/angular-animate.min.js"></script>
<script src="https://code.angularjs.org/1.6.4/angular-touch.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/2.5.0/ui-bootstrap-tpls.min.js"></script>
<script>
angular.module("myApp", ['ngAnimate', 'ui.bootstrap'])
</script>
<script src="script.js"></script>
</head>
<body ng-controller="myCtrl">
<div>
<table class="table">
<tbody>
<tr>
<th>id</th>
<td>{{shop.id}}</td>
</tr>
<tr>
<td>
products
<br>
<button type="button" class="btn btn-default" ng-click="addProduct()"><span class="glyphicon glyphicon-plus" aria-hidden="true" style="margin-right:4px"></span>add product</button>
</td>
<td>
<table class="table">
<tbody>
<tr>
<td>producId</td>
<td>desc</td>
</tr>
<tr ng-repeat="product in shop.products">
<td>
<select ng-model="product.productId" ng-options="selectBoxItem.id as selectBoxItem.id disable when selectBoxItem.isDisabled for selectBoxItem in allSelectBoxItems"></select>
</td>
<td>
{{product.desc}}
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>

AngularJs: store and retrieve data in local storage

I am very new to Angular. Earlier I was using Javascript, but now I am learning AngularJs. Version currently using is 1.3.2.
Problem is I am trying to use local storage.
In Javascript, we use something similar to this:
localStorage.pic = data.pic;
localStorage.id = data.uid;
localStorage.name = data.name;
Is there anything similar to this in AngularJs?
Thanks for your advise.
It's the same way using ngStorage,
Add ngStorage reference and inject it as a depdency to your angular app,
<script type="text/javascript" src='https://rawgithub.com/gsklee/ngStorage/master/ngStorage.js'></script>
angular.module('gameApp', ['ngStorage'])
Then you can store and retrieve like this,
$localStorage.pic= $scope.pic;
DEMO
angular.module('gameApp', ['ngStorage', 'ui.bootstrap'])
.controller('MainCtrl', ['$scope', '$localStorage', function ($scope, $localStorage) {
// Set a total score variable equal to zero
$scope.total = 0;
// NOTE: use d3.js for data visualization in widget
var gameData = [
{
"level": "Level One",
"points": 30,
"max": 100,
"completed": false
},
{
"level": "Level Two",
"points": 50,
"max": 100,
"completed": false
}
];
// tie the game JSON to the view
$scope.gameData = gameData;
// tie the view to ngModule which saves the JSON to localStorage
$localStorage.gameData = gameData;
// loop through the gameData and sum all the values where the key = 'points'
console.log("Your current score is: " + $scope.total)
$localStorage.total = $scope.total;
$scope.addToLevel = function(level, num){
$scope.levelPoints = gameData[level].points += num;
console.log("You have " + $scope.levelPoints + " points in Level");
}
// create a function that loops the json to check if the points >= max
// and if so
// then change completed to true
$scope.calcTotal = function(){
for (var i in $scope.gameData){
var level = $scope.gameData[i];
$scope.total += level.points;
}
$localStorage.total = $scope.total;
};
$scope.calcTotal();
}])
<!DOCTYPE html>
<html ng-app='gameApp'>
<head>
<meta charset="utf-8" />
<title>Angular Local storage</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet">
<script type="text/javascript" src='https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js'></script>
<script type="text/javascript" src='https://rawgithub.com/gsklee/ngStorage/master/ngStorage.js'></script>
<script src="https://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.12.1.js"></script>
<script type="text/javascript" src='script.js'></script>
</head>
<body ng-controller='MainCtrl'>
<!-- Fixed navbar -->
<nav class="navbar navbar-default navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Angular JS Local Storage</a>
</div>
</div>
</nav>
<div class='container'>
<div class='row' style='margin-top:100px'>
<button class='btn btn-primary' ng-click="addToLevel(0, 20); calcTotal();">+20 Points Lvl 1</button>
<br>
<table class='table table-hover'>
<thead>
<tr>
<td>Level</td>
<td>Points</td>
</tr>
</thead>
<tbody>
<tr ng-repeat='data in gameData'>
<td>{{ data.level }}</td>
<td>{{ data.points }}</td>
</tr>
<tr>
<td>Total Points</td>
<td>{{total}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
</html>
You can create a common factory service that will save and return the saved local storage data based on the key.
app.factory('storageService', ['$rootScope', function($rootScope) {
return {
get: function(key) {
return localStorage.getItem(key);
},
set: function(key, data) {
localStorage.setItem(key, data);
}
};
}]);
In controller :
Inject the storageService dependency in the controller to set and get the data from the local storage.
app.controller('myCtrl',['storageService',function(storageService) {
// Set local storage data to storageService
storageService.set('key', 'value');
// Get saved local storage data from storageService
var data = storageService.get('key');
});
JavaScript will remain same whether you use angular or other frameworks.You are doing wrong , localStorage has setItem() and getItem() methods .
Try this
localStorage.setItem('pic',data.pic);
localStorage.setItem('id',data.id);
localStorage.setItem('name',data.name);
And retrieval like this
localStorage.getItem('pic');
localStorage.getItem('id');
localStorage.getItem('name');

Angular two way data-binding dosn´t update table in different route

I have an angular app, and an index.html with an ng-view that renders to different views partials/persons.html and partials/newPerson.html.
when i add a new person to the $scope.persons in my controller via the newPerson.html the $scope.persons is updated, but it dosn´t updated the table in the partials/persons.html. if i copy/paste the table into partials/newPerson.html the table is updated automatically. I cant seem to wrap my head around why? they are using the same controller...?
thank´s in advance for your help :)
js/app.js
var app = angular.module('app',['ngRoute']);
app.config(function($routeProvider){
$routeProvider
.when('/persons',{
templateUrl:'partials/persons.html',
controller:'PersonCtrl'
})
.when('/newperson',{
templateUrl:'partials/newPerson.html',
controller:'PersonCtrl'
})
.otherwise({
redirectTo: '/'
});
});
app.controller('PersonCtrl',['$scope', function($scope){
var persons = [
{
id: 1
,name: "Jens",
age : 18}
,{
id: 2,
name: "Peter",
age : 23
}
,{
id: 3
,name: "Hanne"
,age : 23
}
];
$scope.persons = persons;
$scope.nextId = 4;
$scope.savePerson = function(){
if($scope.newPerson.id === undefined)
{
$scope.newPerson.id= $scope.nextId++;
$scope.persons.push($scope.newPerson);
}else{
for (var i = 0; i < $scope.persons.length; i++) {
if($scope.persons[i].id === $scope.newPerson.id){
$scope.persons[i] = $scope.newPerson;
break;
}
}
}
$scope.newPerson = {};
};
index.html
<html ng-app="app" ng-controller="PersonCtrl">
<head>
<title>Routing</title>
<link rel="stylesheet" href="css/styles.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular-route.js"></script>
<script src="https://code.angularjs.org/1.4.7/i18n/angular-locale_da.js"></script>
<script src="angularSrc/app.js"></script>
</head>
<body>
<br>
<div class="container">
<header>
<h1>People Routing</h1>
<nav>
persons
new person
</nav>
</header>
<div ng-view="ng-view">
</div>
</div>
</body>
partials/persons.html
<h3>Persons</h3>
<table >
<thead>
<tr>
<td>Id</td>
<td>name</td>
<td>age</td>
</tr>
</thead>
<tbody>
<tr ng-repeat="p in persons">
<td>{{p.id}} </td>
<td>{{p.name}} </td>
<td>{{p.age}} </td>
</tr>
</tbody>
</table>
partials/newPerson.html
<div >
<h1>New person</h1>
<form class="form-horizontal">
<fieldset>
<div class="form-group">
<input type="text" ng-model="newPerson.name" model="newPerson.name" class="form-control" id="year" placeholder="name">
</div>
<div class="form-group">
<input type="number" ng-model="newPerson.age" model="newPerson.age" class="form-control" id="age" placeholder="age">
</div>
</fieldset>
</form>
<button type="submit" ng-click="savePerson()" >Save</button>
<h2>nextId: {{nextId}}</h2>
</div>
The problem is that you aren't realizing that each use of controller creates new instance.
The scope is destroyed when you leave a controller so if you add to the scope in one instance , that change will be lost when you load controller again on your other route.
You need to use a service to persist the data during the life of each page load.
Simple service example:
app.factory('PersonService', function () {
var persons = [{
id: 1,
name: "Jens",
age: 18
}, {
...
}, {
...
}];
return {
persons: persons
}
});
Then inject in controller and use the service data in controller
app.controller('PersonCtrl',['$scope','PersonService', function($scope,PersonService){
$scope.persons = PersonService.persons;

Angular javascript array is empty?

Angular javascript array is empty?
I have an array of checkboxes databound to an angular scoped list
I need to check a few checkboxes and send bind them to a second angular scoped array:
My HTML:
<tr ng-repeat="item in pagedItems[currentPage]"
ng-controller="DealerComMaintainCtrl">
<td align="center">
<input type="checkbox" id="{{item.IdArticle}}"
ng-value="item.IdArticle"
ng-checked="selected.indexOf(item.IdArticle) > -1"
ng-click="toggleSelect(item.IdArticle)" />
</td>
<td>
<a href="/Dealercoms/ArticleDownload?FileName={{item.FileName}}&IdArticle={{item.IdArticle}}"
class="btn btn-xs btn-total-red btn-label"><i class="ti ti-download"></i></a>
</td>
<td>{{item.DateArticle | date:'dd/MM/yyyy'}}</td>
<td>{{item.Title}}</td>
<td>{{item.Archive}}</td>
</tr>
And JS in the controller:
$scope.selected = [];
$scope.toggleSelect = function toggleSelect(code) {
var index = $scope.selected.indexOf(code)
if (index == -1) {
$scope.selected.push(code)
} else {
$scope.selected.splice(index, 1)
}
}
$scope.ArchiveDocs = function() {
var selectedoptionz = $scope.selection;
console.log(selectedoptionz);
};
I tried your code and i fixed the problem, by adding the controller on an element above the ng-repeat. The alert is only to check, what is in the selected-array. This is the code, which works fine on my system:
<html>
<head>
</head>
<body ng-app="app">
<table ng-controller="DealerComMaintainCtrl">
<tbody>
<tr ng-repeat="item in pagedItems" >
<td align="center">
<input type="checkbox" id="{{item.IdArticle}}" ng-value="item.IdArticle" ng-checked="selected.indexOf(item.IdArticle) > -1" ng-click="toggleSelect(item.IdArticle)" />
</td>
<td><i class="ti ti-download"></i></td>
<td>{{item.DateArticle | date:'dd/MM/yyyy'}}</td>
<td>{{item.Title}}</td>
<td>{{item.Archive}}</td>
</tr>
</tbody>
</table>
<!-- jQuery -->
<script src="./jquery-2.1.4/jquery.min.js"></script>
<!-- AngularJS -->
<script src="./angular-1.4.5/angular.min.js"></script>
<script>
var app = angular.module("app", []);
app.controller("DealerComMaintainCtrl", function($scope){
$scope.pagedItems = [
{IdArticle: 1, Title: "test1", Archive: "archiv1"},
{IdArticle: 2, Title: "test2", Archive: "archiv1"},
{IdArticle: 3, Title: "test3", Archive: "archiv1"},
{IdArticle: 4, Title: "test4", Archive: "archiv1"}
];
$scope.selected = [];
$scope.toggleSelect = function toggleSelect(code) {
var index = $scope.selected.indexOf(code)
if (index == -1) {
$scope.selected.push(code)
}
else {
$scope.selected.splice(index, 1)
}
alert(JSON.stringify($scope.selected));
}
});
</script>
</body>
</html>
Just try it, i hope it solve your problem...

Resources