Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally apply one-time binding in angular

I came across a situation where I have a lot of items in my list and some of them are in their final state and wouldn't change and some are going to change. I was thinking, is there a way to use Angular's one time binding ('::') conditionally? Like if I have a final flag true - use one time binding, otherwise - regular binding.

Would I have to duplicate my entire DOM structure with ng-if and have one with one-time binding and the other with regular one?

like image 387
waterplea Avatar asked May 12 '26 19:05

waterplea


1 Answers

The most modular way is to declare custom directive that recompiles the DOM element from:

<div is-final='true' ng-model='myvar'></div>

<div is-final='false' ng-model='myvar'></div>

to:

<div>{{::myvar}}</div>

<div>{{myvar}}</div>

wrapping the if clause into the directive. This way you do not have to duplicate many LOC. The directive needs only to require ngModel, a template, replace: true and link. You can also avoid use template and $compile in link.

like image 84
morels Avatar answered May 14 '26 09:05

morels



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!