I have created a pager widget using template file which I am using twice in my HTML page. I have a select for go to page option and also links for previous and next page.
Problem is that when I use select box for updating current page its updated and then I use previous and next page links, the current page gets updated but select box doesn't get updated.
Please tell me what I am doing wrong. Is there any logical mistake in my approach to building a pager widget like this?
Controller Code:
var gallery = angular.module('gallery', []);
gallery.controller('ItemListCtrl', ['$scope', function($scope){
/* Pagination Code */
$scope.currentPage = 1;
$scope.itemsPerPage = 24;
$scope.total = 100;
$scope.range = function(min, max, step){
step = step || 1;
var input = [];
for (var i = min; i <= max; i += step) input.push(i);
return input;
};
$scope.prevPage = function (){
if($scope.currentPage > 1){
$scope.currentPage--;
}
};
$scope.nextPage = function (){
if($scope.currentPage < $scope.pageCount()){
$scope.currentPage++;
}
};
$scope.pageCount = function (){
return Math.ceil($scope.total / $scope.itemsPerPage);
};
$scope.setPage = function (n){
if(n >= 0 && n <= $scope.pageCount()){
$scope.currentPage = parseInt(n, 10);
}
};
}]);
Here is the plnkr URL for reproducing the issue.
http://plnkr.co/edit/9LUJnVzWAS9BauyORQn5?p=preview
The root cause is ng-include
will create a separate scope for targeted element, so a quick fix to your code is adding $parent
prefix to all scope objects.
<fieldset class="pager">
<div>Page {{$parent.currentPage}} of {{$parent.pageCount()}}</div>
<div>
<div>
<label>Go to page</label>
<select ng-model='$parent.currentPage' ng-change="$parent.setPage($parent.currentPage)">
<option ng-repeat="n in range(1,$parent.pageCount())" value="{{n}}" ng-selected="n === $parent.currentPage">{{n}}</option>
</select>
</div>
<div>
<a href ng-click="$parent.prevPage()">Previous Page</a>
|
<a href ng-click="$parent.nextPage()">Next Page</a>
</div>
</div>
</fieldset>
Per Angular document Understanding Scopes, Scope inheritance won't work as you expected when you try 2-way data binding (i.e., form elements, ng-model) to a primitive. This issue with primitives can be easily avoided by following the "best practice" of always have a '.' in your ng-models
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With