DavidC
DavidC

Reputation: 1862

Angularjs 1.5x: How to call a function only once in a template and reuse the result in multiple places

I have a count of questions left in each section and that count is displayed to the user unless there are zero left in which case I display a check mark.

<p class="list-group-item-heading">{{section.title}}
    <i ng-show="questionsLeft(section)==0" class="fa fa-check"></i>
    <span ng-show="questionsLeft(section)>0" class="label">                
            {{questionsLeft(section)}}</span>
</p>

The function questionsLeft() is called 3 times - how can it be called once and its result reused? I have tried both ng-init and the {{x = questionsLeft(section); ""}} trick both of which initialize the variable but it does not update when the value changes.

Upvotes: 1

Views: 856

Answers (1)

Mikhail Romanov
Mikhail Romanov

Reputation: 1612

  1. Create a variable inside section component controller.
  2. Put this variable instead of the function inside you template.
  3. Update variable value each time the number of questions is changed with questionsLeft function. You can do it inside $onChanges hook, for instance.

P.S. it will be easier to say if you provide the controller code

Upvotes: 1

Related Questions