How to watch a primitive service variable in controller with AngularJS?

后端 未结 1 840
生来不讨喜
生来不讨喜 2021-02-05 17:40

I\'m trying to use $watch for it. The $watch body firing at page initialization (with undefined in newValue) and not firing at \"btnChangeIsLoggedIn\" click.

<         


        
相关标签:
1条回答
  • 2021-02-05 18:06

    You can pass a function that will return the value of the Service's method. Angular will then compare it to the previous value.

    $scope.$watch(function(){
        return authService.isLoggedIn;
    }, function (newValue) {
        alert("isLoggedIn changed to " + newValue);
    });
    

    Demo: http://jsfiddle.net/TheSharpieOne/RA2j7/2/

    Note: the reason the text field value doesn't update is because the button only changes the service's value, not the $scope's You can also get rid of that initial alert (running of the change function) but comparing the newValue to the oldValue and only executing the statements if they are different.

    0 讨论(0)
提交回复
热议问题