1

我正在尝试创建一个简单的分页器指令。这个想法是我有一个基于类别的动态表。例如:Category-> Fruits, table will have Apple, Bananas, Oranges etc Category -> Vegetables, table will have Spinach, Cauliflower 等

我正在尝试构建一个动态分页器指令

代码如下

myApp.directive("myPaginator",function(){
    return {
        restrict:"AE",
    replace:true,
        scope:{
            displayPage :"=",
        numPages : "="
        },
        link:function(scope, element, attrs, ctrl){                

        scope.$watch(scope.numPages, function(){
           console.log("New num pages:"+scope.numPages);
           scope.nPages = parseInt(scope.numPages,10);      
           scope.pages=[];
           for (var i=0;i<scope.nPages;i++) {
                scope.pages.push({value:''+(i+1),text:'Page '+(i+1)});
           }
        }, true);
        console.log("Watch is bound");

        },
        controller:function($scope){        
            $scope.onPrevClick=function(newIndex){
                $scope.displayPage = $scope.displayPage -1;
            }

            $scope.onNextClick=function(newIndex){
                $scope.displayPage = $scope.displayPage +1;
            }

        $scope.onFirstClick=function(newIndex){
                $scope.displayPage = 1;
            }

            $scope.onPrevClick=function(newIndex){
                $scope.displayPage = $scope.numPages;
            }

        },
        template:"<div style='clear:both' class='pagination'><ul >"+
        "<li> <a ng-click=\"\">First</a></li>"+
        "<li ><a ng-click=\"\">Previous</a></li>"+
        "<li ><a ng-click=\"\">Page :<select ng-model='displayPage' "+
        "   ng-options='option.value as option.text for option in pages' ng-change=\"gotoPage()\">"+
        "</select></a></li>"+
        "<li ><a ng-click=\"\">Next</a></li>"+
        "<li ><a ng-click=\"\">Last</a></li>"+
                "</ul></div>"
    };

})

用法

<div my-paginator num-pages='numPages' display-page='currPage'></div>

每次用户选择一个新类别时,numPages 都会改变。我面临的问题是 numPages 上的 $watch 永远不会被调用,即使表中的值发生了变化

4

1 回答 1

3

观察范围元素的语法是

scope.$watch('numPages', function () {
    // ...
});
于 2013-05-22T15:46:32.350 回答