3

One of my mates in work show me a really weird behavior of one-time binding in angular.

UseCase:

When you have an element which text is binding by that one-time binding inside block which is conditional by ng-if, then if we change that value, for example adding some letters, and later change the condition of ng-if, and after that the value from one-time binding has been refreshed.

HTML:

  <div ng-if="a" class="blue">{{ ::text }}</div>

It is a kind of bug, or expected behaviour?

Here is an example of what I'm doing: http://codepen.io/samot/pen/rLJAdN

morels
  • 2,095
  • 17
  • 24
Samot
  • 103
  • 1
  • 7

2 Answers2

7

If the condition of ng-if is made false and then true, it will recreate its contents, causing the one-time ng-bind directive to be evaluated again.

The only thing one time binding does is to avoid adding a watch on your expression, but it doesn't "cache" or "store" the result for the case the content of a directive is compiled again.

So it's expected behavior.

jjmontes
  • 24,679
  • 4
  • 39
  • 51
  • Yeah, i know that, but there is a kind of bug, or expected behaviour? – Samot Jul 19 '16 at 12:50
  • It's expected behavior. Imagine your content is inside ng-repeat using a list. Whenever the list changes and rows are created or recreated, they are evaluated again even if the expressions are one-time bindings. – jjmontes Jul 19 '16 at 12:51
  • If you were using `ng-show` instead of `ng-if` the value wouldn't change, since this time the content would just change visibility instead of being recreated. – Aaron Jul 19 '16 at 12:52
  • 2
    If you don't like this behavior just make ng-if one-time binding `ng-if="::a"` Look at you HTML when running angular app. ng-show only define display:none on element whereas ng-if compile html each time it changes condition. – krutkowski86 Jul 19 '16 at 12:54
2

Works as expected because using ngIf directive the code is completely recompiled. If you use ngShow the behavior changes and code behaves as you are expecting from ngIf. This because code is only hidden and not recompiled, so not causing the re-(first)-evaluation of the variable.

Community
  • 1
  • 1
morels
  • 2,095
  • 17
  • 24