Angular JS ng-include 绑定问题

Angular JS ng-include binding issues

我使用模板文件创建了一个寻呼机小部件,我在 HTML 页面中使用了两次。我有一个 select 用于转到页面选项以及上一页和下一页的链接。

问题是,当我使用 select 框更新当前页面时,它已更新,然后我使用上一页和下一页链接,当前页面得到更新,但 select 框没有得到更新.

请告诉我我做错了什么。我构建这样的寻呼机小部件的方法是否存在逻辑错误?

控制器代码:

 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);
      }
    };
  }]);

这是重现问题的 plnkr URL。

http://plnkr.co/edit/9LUJnVzWAS9BauyORQn5?p=preview

根本原因是 ng-include 将为目标元素创建一个单独的范围,因此对代码的快速修复是向所有范围对象添加 $parent 前缀。

<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>

每个 Angular 文档 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