AngularJS:从作用域调用$watchGroup

AngularJS: calling $watchGroup from scope

本文关键字:watchGroup 调用 作用域 AngularJS      更新时间:2023-09-26

如何调用指令的$watctGroup表单链接函数。我有两个简单的scope元素(integer),我想成对地观察它们。我想$watchGroup比使用$watch('[element1,element2'],..)更有效。

像这样:

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

更新:

请记住,$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!');
            });
        }
    }
 });

柱塞