0

I have a variable I need to put in a template, but it's only created and never updated or removed. It is, however, referenced in multiple areas of the template. It's used in ng-repeat, so it's an object. Not sure if that matters.

But I want to reference the variable once and stop angularjs from watching it. Is this possible?

Brooklyn Nicholson
  • 646
  • 10
  • 25
  • 3
    https://docs.angularjs.org/guide/expression#one-time-binding – JB Nizet Jan 29 '15 at 18:27
  • I think one approach would be to do this with custom directives using `scope: { myReadOnly: '&myAttrName' }`. That gives you a function on the scope that returns the evaluated property, and you could choose to only read it one time. But ngRepeat is bi-directional out of the box, so you might need to roll a custom ngRepeat that doesn't bind. – Semicolon Jan 29 '15 at 18:29
  • http://stackoverflow.com/questions/16125872/why-ng-bind-is-better-than-in-angular – Koitoer Jan 29 '15 at 18:31
  • @JBNizet That's awesome, I didn't know about that. I don't think it solves the ng-repeat issue, but it's fantastic information. – Semicolon Jan 29 '15 at 18:31
  • @JBNizet it works, actually. it doesn't work if you try to pass it as a variable to another directive, but that can be worked around. – Brooklyn Nicholson Jan 29 '15 at 19:06

1 Answers1

2

Are you familiar with bind once?

Angular internally creates a $watch for each ng-* directive in order to keep the data up to date, so in this example just for displaying few info it creates 6 + 1 (ngRepeatWatch) watchers per person, even if the person is supposed to remain the same once shown. Iterate this amount for each person and you can have an idea about how easy is to reach 2000 watchers. Now if you need it because those data could change while you show the page or are bound to some models, it's ok. But most of the time they are static data that don't change once rendered. This is where bindonce can really help you.

https://github.com/Pasvaz/bindonce

<ul>
    <li bindonce ng-repeat="person in Persons">
        <a bo-href="'#/people/' + person.id"><img bo-src="person.imageUrl"></a>
        <a bo-href="'#/people/' + person.id" bo-text="person.name"></a>
        <p bo-class="{'cycled':person.generated}" bo-html="person.description"></p>
    </li>
</ul>
Nick Satija
  • 181
  • 7