最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - AngularJS: calling $watchGroup from scope - Stack Overflow

programmeradmin0浏览0评论

How can I call $watctGroup form link function of directive. I've got two simple scope elements (integer) and I'd like to watch them in pair. I suppose $watchGroup is more effective than to use something like $watch('[element1, element2'],..).

How can I call $watctGroup form link function of directive. I've got two simple scope elements (integer) and I'd like to watch them in pair. I suppose $watchGroup is more effective than to use something like $watch('[element1, element2'],..).

Share Improve this question asked Sep 19, 2014 at 20:43 user1795707user1795707 231 silver badge3 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 5

Like this:

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

Update:

Bare in mind that $watchGroup started being available in AngularJS 1.3, if you are using a previous version it won't work.

Example of how to use $watchGroup in a directive:

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!');
            });
        }
    }
 });

PLUNKER

发布评论

评论列表(0)

  1. 暂无评论