简体   繁体   中英

Why does one AngularJS service bind work but the other doesn't

If you take the following Plunkr you will see a simple service - increments a count and it gets reported to the user.

What I am trying to understand is why this works ( the increment is reported to the user on a click ) - binding to the function in the view:

From the HTML

<p> This is my countService variable : {{countService()}}</p>

From the controller

$scope.countService = testService.getCount

And why this Doesn't work - binding the function to the scope:

From the HTML

<p> This is my countService variable : {{countService}}</p>

From the controller

$scope.countService = testService.getCount()

Ultimately we're binding to a function in the service, though the second one doesn't bind the new value.

A clear, easy to understand, explanation would be great :)

In the first version you bind directly to the function so angular checks if the functions output has changed. In the second version you only call the function once when the scope is created and set countService to that value. Since countService now is a variable that has nothing to do with the counting function its value wont reflec the value returned from that function.

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