AngularJS:从范围调用$ watchGroup

use*_*707 1 javascript angularjs angularjs-directive angularjs-scope

如何调用$ watctGroup表单链接函数的指令.我有两个简单的范围元素(整数),我想成对观看它们.我认为$ watchGroup比使用$ watch('[element1,element2'],...)之类的东西更有效.

Jos*_*sep 5

像这样:

scope.element1=1;
scope.element2=2;
scope.$watchGroup(['element1','element2'], function(){/* your code here */});
Run Code Online (Sandbox Code Playgroud)

更新:

请记住,$watchGroup开始在AngularJS 1.3中可用,如果您使用的是以前的版本,则无法使用.

如何$watchGroup在指令中使用的示例:

angular.module ('testApp' , [])
.directive ('testDirective', function (){
    return{
        restrict:'A',
        replace:true,
        template: '<div ng-click="inc()">{{element1}} <br/> {{element2}}</div>',
        link: function(scope, element, attrs){
            scope.element1=0;
            scope.element2=0;
            scope.inc = function(){scope.element1++;scope.element2--};
            scope.$watchGroup(['element1', 'element2'], function(){
                console.log('something changed!');
            });
        }
    }
 });
Run Code Online (Sandbox Code Playgroud)

PLUNKER