angularjs pagination: Unknown provider: ngTableParamsProvider - angularjs

I want to implement the pagination in angular js.
I am new to angular js.
I get this error in browser:
Error: [$injector:unpr] http://errors.angularjs.org/1.3.15/$injector/unpr?p0=ngTableParamsProvider%20%3C-%20ngTableParams%20%3C-%20allUsersCtrl
I have included these files at the HEAD section of layout view:
<!-- angular js--->
<script src="<?php echo base_url();?>angular/js/angular.min.js"></script>
<script src="<?php echo base_url();?>angular/js/angular-route.min.js"></script>
<!-- flash msg -->
<script src="<?php echo base_url();?>angular/js/angular-flash.js"></script>
<!-- flash msg -->
<!--loading bar-->
<script src="<?php echo base_url();?>angular/js/loading-bar.min.js"></script>
<script src="<?php echo base_url();?>angular/js/angular-animate.min.js"></script>
<script src="<?php echo base_url();?>angular/js/ng-table.min.js"></script>
<!--loading bar-->
<script src="<?php echo base_url();?>angular/js/demo_angular.js"></script>
<script src="<?php echo base_url();?>angular/js/app.js"></script>
This is my table in partial html:
<table ng-table="tableParams" class="table table-striped table-bordered table-hover" id="table_all_users">
<thead>
<tr>
<th width="20%"><input type="checkbox" name="chk_all" id="chk_all" onchange="checkAll(this)" /> Select</th>
<th width="15%">Sr. No.</th>
<th width="35%">User Name</th>
<th width="25%">First Name</th>
<th width="25%">Last Name</th>
<th width="15%">Mobile</th>
<th width="15%">Email</th>
<th width="15%">Action</th>
</tr>
</thead>
<tbody ng-init="get_users()">
<tr class="gradeX" ng-repeat="user in allUsers | filter:query">
<td width="20%"><input type="checkbox" name="list[]" class="chk_all" value="" id="" onclick="uncheck_select_all(this);" /></td>
<td width="15%">{{ $index + 1 }}</td>
<td width="35%">{{ user.username }}</td>
<td width="25%">{{ user.fname }}</td>
<td width="25%">{{ user.lname }}</td>
<td width="15%">{{ user.mobile }}</td>
<td width="15%">{{ user.email }}</td>
<td width="15%"><a title="Edit User" href="#/edit_user/{{user.user_id}}" ><span class="fa fa-pencil"></span></a> | <a title="Delete User" id="" style="cursor:pointer;" ng-click="delete_user(user.user_id)" ><span class="fa fa-trash-o"></span></a></td>
</tr>
</tbody>
</table>
This is the script.
var angularControllers = angular.module('angularControllers', ['flash']);
angularControllers.controller('allUsersCtrl', ['$scope','$http','$filter','Flash','ngTableParams', function($scope,$http,$filter,Flash,ngTableParams){
$scope.get_users = function()
{
$http.get("../admin/users/angular_all_users").success(function(data)
{
$scope.allUsers = data;
});
}
//for sorting by table column
var orderBy = $filter('orderBy');
$scope.order = function(predicate, reverse)
{
$scope.allUsers = orderBy($scope.allUsers, predicate, reverse);
}
//table pagination
$scope.tableParams = new ngTableParams({
page: 1, // show first page
count: 10 // count per page
}, {
total: data.length, // length of data
getData: function ($defer, params) {
$defer.resolve(data.slice((params.page() - 1) * params.count(), params.page() * params.count()));
}
})
}]);
When I am adding here as: ['flash','ngTable']
still it gives error : data is not defined
Also after trying to implement pagination my data is not going to display, only header row is display.
Please suggest me any solution or any link that will guid step by step for pagination

My advice to you is always to initialize the ng-table in $http.get. It must be like:
$http.get('../admin/users/angular_all_users').success(function (data) {
$scope.tableParams = new ngTableParams({
page: 1,
count: 10
},
{
total: data.length,
getData: function ($defer, params) {
// use build-in angular filter for ordering
var orderedData = params.sorting() ?
$filter('orderBy')(data, params.orderBy()) : data;
$defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
}
});
});
With this "best practice" you will always avoid the problem that data with it's properties is undefined.
Don't forget to include ngTable in your module.
Hope this will push you forward.
Best regards!

You are getting the error because you are trying to include a dependency called ngTableParams which I think is in the module called ngTable which you have not included.
When you include the module as well, you are getting data is undefined. This is because you are using data variable in line
total: data.length, // length of data
but you have not declared the variabled before usage. I think you missed that.
You can just check the line number in the error to determine what is the problem. Try putting breakpoints, so you can easily trace the issues.

I also meet this error
/**
* #ngdoc service
* #name ngTableParams
* #description Backwards compatible shim for lowercase 'n' in NgTableParams
*/
angular.module('ngTable').factory('ngTableParams', ['NgTableParams', function(NgTableParams) {
return NgTableParams;
}]);
the above code can find in angular-ngtable.js, but I don't use this version, I success when I replace this, or change ngtableParams to uppercase (recommand).

Related

I just want to load a particular div on some actions in angular js

I just want to load a particular div on some actions in angular js.
<div class="row">
<div class="col-md-12">
<div id = "div_1" class="table-responsive" ng-controller="usercontroller" ng-init="displayData() ">
<table class="table table-hover table-bordered">
<thead align="center">
<tr>
<th>Service Request Number</th>
<th>Name of service request</th>
<th>Date of request</th>
<th>Closure date</th>
<th>Current state</th>
<th>Current owner</th>
<th>Link to share point folder</th>
<th>Schedule variance</th>
<th align="center">Details</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="x in service track by $index">
<td><span ng-bind="x.id"></span></td>
<td><span ng-bind="x.sales_force_id"></span></td>
<td><span ng-bind="x.submission_date"></span></td>
<td><span ng-bind="x.closure_deadline"></span></td>
<td><span ng-bind="x.item_status"></span></td>
<td></td>
<td></td>
<td></td>
$scope.displayData = function()
{
alert($scope.firstRole);
alert("nishant singh");
if(empIVal == 1 && $scope.firstRole == 'Initiator' ){
alert("i am a initiator");
$http.get("commonGet.jsp?sqlStr=select * from service_request.service_request_data where emp_id="+empHidVal+ " order by id desc")
.then(function(response){
$scope.service = response.data;
});
}
Here I want to load the div again when the displayFunction() is called and response is been returned. Also, the response is JSON object. I am able to call the function using ng-change directive and also able to get the desired JSON object, but I don't know how to load the div again after the response.
wrap your assignment to service variable in timeout so that angular is aware of the changes
$timeout(function(){
$scope.service = response.data;
});
Thus your whole method becomes something like this.
$http.get("commonGet.jsp?sqlStr=select * from service_request.service_request_data where emp_id="+empHidVal+ " order by id desc")
.then(function(response){
$timeout(function(){
$scope.service = response.data;
});
});
}

angularjs > router resolve > "Error: [$injector:unpr] Unknown provider"

im trying to add a resolve\promise to my project, so when you ask for a page it will load up only after receiving the json from the server.
this is my js code:
'use strict';
angular.module('myApp.show', ['ngRoute'])
.config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/show', {
templateUrl: 'views/show.html',
controller: 'showCtrl',
resolve: {
booksList: function ($http) {
return ($http.get('data/books.json')
.then(function (data) {
return data;
}));
}
}
});
}])
.controller('showCtrl', ['booksList', '$scope', function (booksList, $scope) {
$scope.books = booksList;
$scope.removeRow = function (productIndex) {
if (window.confirm("are you sure?")) {
$scope.books.splice(productIndex, 1);
}
}
}])
but this is what i get:
Error: [$injector:unpr] Unknown provider: booksListProvider <- booksList <- showCtrl
i kinda new to angular, but i followed several tutorials and while it worked in the video - i keep getting errors.
html:
<div class="table-responsive">
<div ng-app="myApp.show" ng-controller="showCtrl"> <!-- ctrl -->
<table st-table="rowCollection" class="table table-striped">
<thead>
<tr>
<th st-sort="author">Author</th>
<th st-sort="date">Date</th>
<th st-sort="title">Title</th>
<th></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="(bookIndex, book) in books">
<td class="col-md-3">{{ book.author }}</td>
<td class="col-md-3">{{ book.date | date }}</td>
<td class="col-md-4">{{ book.title | beutifyTitle }}</td>
<td class="col-md-1"><ng-include src="'views/partials/editBook.html'"></ng-include></td>
<td class="col-md-1"><button class="btn btn-warning" ng-click="removeRow()">Delete</button></td>
</tr>
</tbody>
</table>
</div>
</div
You should be removing ng-controller="showCtrl" from your template. The reason being is, you are assing showCtrl via router already. But as you are again wrote ng-controller over inline template in that case it fails to get booksList resolve provider.

angularjs how to ng-repeat array values as column headings

How to ng-repeat the values of the below array as the column headings for my ng-table?
I am trying to display the value from $scope.cols array as the column headings of my table, in other words as the fields, and display all the rows.
here is my try:
<div ng-controller="mycontroller as projects">
<table ng-table-dynamic="projects.tableParams with projects.cols"
show-filter="true" class="table table-bordered table-striped">
<tr ng-repeat="row in $data">
<td ng-repeat="col in $columns">{{::row[col.field]}}</td>
</tr>
</table>
</div>
and here is my controller:
app.controller('mycontroller', ["$scope", "$filter", "ngTableParams", "DatabaseRef", "$firebaseArray",
function ($scope, $filter, ngTableParams, DatabaseRef, $firebaseArray) {
//show all projects
var showallprojects = DatabaseRef.ref("projects").orderByKey();
$scope.allprojectslist = $firebaseArray(showallprojects);
var data = $scope.allprojectslist;
data.$loaded().then(function(data) {
console.log(data.length); // data is loaded here
$scope.cols = Object.keys(data[0]);
console.log($scope.cols);
$scope.tableParams = new ngTableParams({
page: 1, // show first page
count: 7, // count per page
sorting: { country: "asc" },
filter : {
}
}, {
filterSwitch: true,
total: 0, //data.length, // length of data
getData: function ($defer, params) {
// use build-in angular filter
var filteredData = params.filter() ?
$filter('filter')($scope.allprojectslist, params.filter()) :
$scope.allprojectslist;
var orderedData = params.sorting() ?
$filter('orderBy')(filteredData, params.orderBy()) :
$scope.allprojectslist;
params.total($scope.allprojectslist.length);
// set total for recalc pagination
$defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
}
});
});
}]);
note:
the ngtable dynamic model is taken from here and the doc is here.
EDIT
I've probably misunderstood your question, I thought the code above wasn't a copy of st-table examples.
In your scenario, if you want to display each $scope.cols value as a heading you need to ng-repeat="col in cols" and print out your current col value {{col}}.
I'm assuming your data inside the body of the table to be an array of objects, and each object to be in the form of [col] => value.
I'm updating the code sample below.
You simply need to structure better your table.
<div ng-controller="mycontroller as projects">
<table ng-table-dynamic="projects.tableParams with projects.cols"
show-filter="true" class="table table-bordered table-striped">
<thead>
<tr>
<th ng-repeat="col in cols">{{col}}</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="row in data">
<td ng-repeat="col in col">{{ row[col] || "empty"}}</td>
</tr>
</tbody>
</table>
</div>
So basically we're cycling the $columns array once for building the heading of the table; then we cycle the $data array to get an array of objects (I suppose), and each iteration is a new row; then inside of each row we cycle the $columns array again to get the col.field we're looking for, and each iteration will be a new <td> inside our row.
Hope this helps.

angular angular-table dynamic header name

I use angular and angular-table to display multiple tables on the same page.
I need to create dynamic table with dynamic header and dynamic content.
Plunkr her
This is a working example with non dynamic header but I don't find how to make dynamic
The controller :
angular.module('plunker', ['ui.bootstrap',"angular-table","angular-tabs"]);
function ListCtrl($scope, $dialog) {
$scope.cols= ['index','name','email'];
$scope.list = [
{ index: 1, name: "Kristin Hill", email: "kristin#hill.com" },
{ index: 2, name: "Valerie Francis", email: "valerie#francis.com" },
...
];
$scope.config = {
itemsPerPage: 5,
fillLastPage: true
};
}
HTML
<!-- this work -->
<table class="table table-striped" at-table at-paginated at-list="list" at-config="config">
<thead></thead>
<tbody>
<tr>
<td at-implicit at-sortable at-attribute="name"></td>
<td at-implicit at-sortable at-attribute="name"></td>
<td at-implicit at-sortable at-attribute="email"></td>
</tr>
</tbody>
</table>
<!-- this fail ... -->
<table class="table table-striped" at-table at-paginated at-list="list" at-config="config">
<thead></thead>
<tbody>
<tr>
<td ng-repeat='col in cols' at-implicit at-sortable at-attribute="{{col}}"></td>
</tr>
</tbody>
</table>
I am missing some think or it is not possible with this module ?
Did you know another module where you can have dynamic header and pagination ? ( i try also ngTable but have some bug issu with data not being displayed )
Through the below code, you can generate dynamic header
<table class="table table-hover table-striped">
<tbody>
<tr class="accordion-toggle tblHeader">
<th ng-repeat="(key, val) in columns">{{key}}</th>
</tr>
<tr ng-repeat="row in rows">
<td ng-if="!$last" ng-repeat="col in key(row)" ng-init="val=row[col]">
{{val}}
</td>
</tr>
</tbody>
</table>
Angular Script
var app = angular.module('myApp', []);
app.controller('myControl', function ($scope, $http) {
$http.get('http://jsonplaceholder.typicode.com/todos').success(function (data) {
$scope.columns = data[0];
$scope.rows = data;
}).error(function (data, status) {
});
$scope.key = function (obj) {
if (!obj) return [];
return Object.keys(obj);
}
});

Angularjs: Why is $scope.variable in $watch not up-to-date?

I created a Plunker here to illustrate the problem. Here is the main code:
<body ng-controller="MainCtrl">
<table class="table table-bordered table-striped table-condensed table-hover">
<caption class="text-left" style="background-color: lightgray">
Search: <input ng-model="searchString" style="width: 80px" />
Filted count: {{filteredList.length}}
</caption>
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Sex</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="emp in filteredList = (data.employees | filter:searchString)">
<td>{{emp.firstName}}</td>
<td>{{emp.lastName}}</td>
<td>{{emp.sex}}</td>
</tr>
</tbody>
</table>
</body>
App.js:
$scope.searchString = '';
$scope.$watch('searchString', function(str) {
console.log($scope.filteredList.length);
});
The problem is that the console.log of filteredList.length is always one loop behind (compared to html which is correct), that is, from previous filter. How can I fix it?
You are logging filteredList.length as soon as searchString changes. But, at at moment, filteredList has not yet been modified by the filter in ngRepeat.
One way to fix this would be to $watch filteredList.length instead:
$scope.$watch(function() {
return ($scope.filteredList || []).length;
...
Update
I really like shaunhusain's comment. His suggestion is probably closer to what you really want to do.
$scope.searchString = '';
// Initialize filteredItems as a copy of data.employees
$scope.filteredItems = angular.copy($scope.data.employees);
// Watch your search string instead and apply filtering using $filter
$scope.$watch(function() {
return $scope.searchString;
},
function(str) {
$scope.filteredItems = $filter('filter')($scope.data.employees, {$: $scope.searchString}, false);
console.log($scope.filteredItems.length);
});
Then, your ngRepeat is simply:
<tr ng-repeat="emp in filteredItems">
<td>{{emp.firstName}}</td>
<td>{{emp.lastName}}</td>
<td>{{emp.sex}}</td>
</tr>

Resources