Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular JS ng-include binding issues

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

like image 809
Abdul Haseeb Avatar asked Feb 15 '15 11:02

Abdul Haseeb


1 Answers

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>
&nbsp;|&nbsp; 
<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

like image 87
Rebornix Avatar answered Sep 30 '22 18:09

Rebornix