Sudarshan Kalebere
Sudarshan Kalebere

Reputation: 3929

Angular watch doesnt triggering when I change watcher modal inside $watch

I am calling a factory service to increment counter value, and when counter value is greater than 5 then I am calling again same factory service inside watch. I am using watch to see changed counter value.

My question is when counter becomes greater 5 it calls service but when again inside watch it calls factory service, it stops calling service, as per me it should go in infinite loop right? because when factory service is called the counter is still greater than 5.

Is watch stops checking value of modal when it is modified inside watch?

Here is the Fiddle

JS code

var app = angular.module('myApp', []);

app.factory('testFactory', function(){
    return {
        incrementCount:function(a){
                       a++;
                       console.log('called service'+a)
                      return a;
        }
    }               
});


function HelloCtrl($scope, testFactory)
{
    $scope.counter = testFactory.incrementCount(5);
    $scope.$watch('counter', function (newValue, oldValue) {
        if($scope.counter > 5){
            $scope.counter = testFactory.incrementCount($scope.counter);
        }
    });
}

html code

<div ng-controller="HelloCtrl">
    <p>{{counter}}</p>
</div>

Upvotes: 0

Views: 93

Answers (1)

Ahmed Mostafa
Ahmed Mostafa

Reputation: 696

Because your condition $scope.counter > 5 // === false

You can make it $scope.counter >= 5 or I suggest a new way to do that

Check this link

Upvotes: 1

Related Questions