J. Doe
J. Doe

Reputation: 329

How to deal with async variables in angularJS ng-if?

I've got a condition in ng-if="ctrl.zoo" (in some directive where ctrl.zoo = ctrl.foo && ctrl.bar). The problem is that bar initializes by async function call and angularJS for some reason doesn't update my UI even though I included bar to my scope. I google that it's a bad idea to watch other variables to assign a new value for another (basically watch for changes of bar). It did work perfectly though if I inline ctrl.zoo (e.g.ng-if="ctrl.foo && ctrl.bar"`). Is there any simple fix about it?

Upvotes: 1

Views: 700

Answers (1)

hayzey
hayzey

Reputation: 464

If you assign zoo = foo && bar in your controller, that is the value zoo is going to stay as regardless of whether or not the value of bar changes.

If you want zoo to update, you have a couple of options:

  1. Update the value of zoo again to foo && bar after your async function call is finished.

  2. Write a function in your directive controller called getZoo() which returns foo && bar. Use that function in your directive's template and when you update the value of bar on the directive's scope, the scope will run a digest loop, and that function will return the new value. The reason that inlining ctrl.foo && ctrl.bar in your template works is because you're doing essentially this.

Upvotes: 4

Related Questions