简体   繁体   中英

Angular $scope.$watch on (for in… ) don't work

in my code i have the following for watch changes in some variables

$scope.$watch('ns.namespacea.watchable_value', function(newVal, oldVal){
    //...
})

$scope.$watch('ns.namespaceb.watchable_value', function(newVal, oldVal){
    //...
})

$scope.$watch('ns.namespacec.watchable_value', function(newVal, oldVal){
    //...
})

the previous code work fine but I have many namespaces with a watchable_value and I wanna do

var namespaces = ['namespacea', 'namespaceb', 'namespacec'];

for (i = 0; i < namespaces.length; i++) {
    var namespace = 'ns.' + namespaces[i] + '.watchable_value';
    console.log(namespace) //prints 'ns.namespacea.watchable_value', 'ns.namespaceb.watchable_value, ..
    $scope.$watch(namespace, function(newVal, oldVal){
        //...
    })
}

but the callback never is called

When you use for ... in , you get keys, not values:

for (var namespace in myNamespaces) {
    $scope.$watch('ns.' + myNamespaces[namespace] + '.watchable_value', function(newVal, oldVal){
        //...
    })
}

Just index back into the array and you should be okay.

As I said, I guess it's a callback issue, because this works fine:

$scope.ns= {namespacea: {value: 'testa'},
            namespaceb: {value: 'testb'},
            namespacec: {value: 'testc'}
           };
for (i = 0; i < namespaces.length; i++) {
    var namespace = 'ns.' + namespaces[i] + '.value';
    console.log(namespace);
    $scope.$watch(namespace, function(newVal, oldVal){
        console.log(newVal);
    })
}

http://jsfiddle.net/xdsn8/

So you just have to create a closure to make the callback aware of the namespace and it will work. Like this:

http://jsfiddle.net/xdsn8/1/

when I wrap into closure like commet @SebastienC. works fine

namespaces = ['minuta', 'menu', 'plato'];

callback = function(i) {
  var name = 'ns.' + i + '.value';
  return $scope.$watch(name, function(newVal, oldVal) {
    // ...
  });
};

for (_i = 0, _len = namespaces.length; _i < _len; _i++) {
  i = namespaces[_i];
  callback(i);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM