0

Which solution is best. Set three watches in controller to each data and accordingly set differrent method or set one watch for all three variables and then check which changed and run specified method.

In allegory to event handling, best is to delegate event on parent object and then delegate for parts of dom, according to specified event. If angular permit such watching, how to implement this?

Basic solution is simple, but demands three watches:

$scope.$watch(function() {
    return service.var1;
},
function callback(new,old) {
    $scope.function1();
});
$scope.$watch(function() {
    return service.var2;
},
function callback(new,old) {
    $scope.function2();
});
$scope.$watch(function() {
    return service.var3;
},
function callback(new,old) {
    $scope.function3();
});

Second solution seems to be better, according to event observing, but i don't know how to determine watched element:

$scope.$watch(function() { 
     return service.var1 + service.var2 + service.var3; }, 
  function callback(new,old) { 
  var changed = ;//?here how to determine which variable changed
  switch ( changed ) { 
    case 'var1' : $scope.function1();break; 
    case 'var2' : $scope.function2();break;
    case 'var3' : $scope.function3();break; } 
})

How to implement delegating to watched variables in Angular?

Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
changtung
  • 1,614
  • 15
  • 19

1 Answers1

1

I would preferred second way you used but there should be $$watchGroup

Code

$scope.$watchGroup(['service.var1', 'service.var2', 'service.var3'],
  function(newVal, oldVal) {
    var changed = ''
    if (newVal[0] != oldVal[0])
        changed = 'var1';
    if (newVal[1] != oldVal[1])
        changed = 'var2';
    if (newVal[2] != oldVal[2])
        changed = 'var3';
    switch (changed) {
        case 'var1':
            $scope.function1();
            break;
        case 'var2':
            $scope.function2();
            break;
        case 'var3':
            $scope.function3();
            break;
    }
});

For more info refer this SO answer which has explained the same.

Community
  • 1
  • 1
Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299