Domanda

Angular documentation shows this test case.

       // let's assume that scope was dependency injected as the $rootScope
       var scope = $rootScope;
       scope.name = 'misko';
       scope.counter = 0;

       expect(scope.counter).toEqual(0);
       scope.$watch('name', function(newValue, oldValue) {
         scope.counter = scope.counter + 1;
       });
       expect(scope.counter).toEqual(0);

       scope.$digest();
       // no variable change
       expect(scope.counter).toEqual(0);

Here you can see that scope.name is set before the $watch is added, and that counter remains zero.

I can not reproduce this in jsFiddle.

http://jsfiddle.net/thinkingmedia/3ttKV/

I expect this code to not show an alert the first time. It should only be triggered if name changes.

        $scope.name = 'Nick';
        $scope.$watch('name',function(){
            alert('name changed');
        });

How can I get this to work as documented. I need my scope to be set with some default values, and not have the watchers triggered unless they are changed.

È stato utile?

Soluzione

The listener will be called when the watcher is initialized, in that case, newValue === oldValue, so you need to check that as follow:

$scope.name = 'Nick';
$scope.$watch('name',function(newValue, oldValue){
    if (newValue !== oldValue) {
        alert('name changed');
    }
});
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top