Angular JS ng包含绑定问题



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

问题是,当我使用选择框更新当前页面时,它已更新,然后我使用上一页和下一页链接,当前页面会更新,但选择框不会更新。

请告诉我我做错了什么。在我构建这样一个寻呼机小部件的方法中,有什么逻辑错误吗?

控制器代码:

 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,当您尝试将双向数据绑定(即表单元素、ng模型)到基元时,范围继承不会像您预期的那样工作。通过遵循始终具有"的"最佳实践",可以很容易地避免基元的这个问题在您的ng模型中

最新更新