$ watch在未调用的指令中进行双向绑定

时间:2013-05-22 15:44:21

标签: angularjs angularjs-directive

我正在尝试创建一个简单的paginator指令。我的想法是,我有一个基于类别的动态表。例如: 类别 - >水果,桌子将有苹果,香蕉,橘子等 类别 - >蔬菜,餐桌上都有菠菜,花椰菜等。

我正在尝试构建一个动态的paginator指令

代码在

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

1 个答案:

答案 0 :(得分:3)

观察范围元素的语法是

scope.$watch('numPages', function () {
    // ...
});