poshest poshest - 1 year ago 66
AngularJS Question

AngularJS >=1.3: ng-if with one time binding that is removed when expression evaluates to true

I make heavy use of this trick

ng-if="::vm.isLoaded || undefined"

In this case, if
is anything falsey the watch will continue to operate because
is always returned in that case, and the "one time binding" continues to watch until the expression evaluates to something other than

Is there any way to achieve the reverse? Ie keep watching truthy values until the expression evaluates to
, or some other "magic" value.

A real use case is a Loading... gif, which once the content is loaded, needs to disappear.


works fine (shows the loading gif while loading, and hides it once loaded), but once the stuff is loaded, I want the watch to be removed (the stuff will never become "unloaded" again).

Answer Source

Copying over from GitHub:

Negative ngIf with one-time binding is indeed not possible currently and is a usecase (the only one afaik) that makes ngUnless (the opposite of ngIf) enable something that is not already possible.

A more verbose work-around for achieving what you want is to use ngSwitch (although this adds an extra DOM element - which you can hide of course).

<div ng-switch="::(foo || undefined)">
  <div ng-switch-when="undefined">
    This text will be removed for ever,
    once `foo` evaluates to something truthy

That said, ngIf is just a plain old directive (and not a complex one for that matter), so it is not difficult to copy and modify its source code and include it in your app.

Here is an "ngUnless"-like demo.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download