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 badges1 Answer
Reset to default 5Like 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!');
});
}
}
});