Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - ng-show using method continuously called

Tags:

angularjs

To my understanding ng-show, like other bindings, should stop calling the associated method once the digest stabilizes. With that in mind I would expect to see the following console.log() twice. It is however logging once a second or so.

Is my understanding flawed, my implementation, or is this functioning as expected and I shouldn't worry about any negative performance impacts of such methods being called continuously?

The method (in CoffeeScript)

$scope.showThis = ->
    console.log("foobar")
    true

The HTML tag with the ng-show

<div ng-show="showThis()">hey, you can see me!</div>

Thanks for any insights =]

like image 330
Ryan Crews Avatar asked Jan 04 '14 00:01

Ryan Crews


1 Answers

It is your correct understanding that ng-show would be called once the digest is 'stabilzed'. However, what you maybe fail to understand is that the apply digest cycle might be triggered by many things and so your ng-show would be called for this scope many times. You can debug and check that this scope's apply/digest is being called exactly as many times as your ng-show's method. There are no guarantees it should be called only once, twice or whatever times. As soon as a digest/apply cycle is triggered on your scope, you gonna get your console.log. Simple as that.

Of course, the reasons for triggering a digest/apply cycle might be multiple, but in my opinion eventually it should stop if you don't trigger browser events or don't do reloads or don't do some $timeout stuff. If it doesn't stop, then you messed up somewhere.

I created a Plunkr for you so you can check that in the normal case, it would be called once or twice and if you don't act on it, nothing happens. If you, however press the button, which updates a totally different scope value, it would trigger a scope digest/apply cycle and you would get an additional console.log:

http://plnkr.co/edit/x9I6VGP8eXtLGmT1Cuqu?p=preview

like image 107
Nikola Yovchev Avatar answered Sep 25 '22 19:09

Nikola Yovchev