97

How can I avoid having the {{f = ...}} statement in the third line print out the content of forecast[day.iso]?

I want to avoid using forecast[day.iso].temperature and so on for every iteration.

<div ng-repeat="day in forecast_days">
  {{$index}} - {{day.iso}} - {{day.name}}
  {{f = forecast[day.iso]}}
  Temperature: {{f.temperature}}<br>
  Humidity: {{f.humidity}}<br>
  ...
</div>
1
  • 3
    It might not be an answer, but useful tip is to use {{f = forecast[day.iso];""}} as it would not print anything on the view. Commented Oct 28, 2015 at 7:57

2 Answers 2

197

Use ngInit: https://docs.angularjs.org/api/ng/directive/ngInit

<div ng-repeat="day in forecast_days" ng-init="f = forecast[day.iso]">
  {{$index}} - {{day.iso}} - {{day.name}}
  Temperature: {{f.temperature}}<br>
  Humidity: {{f.humidity}}<br>
  ...
</div>

Example: http://jsfiddle.net/coma/UV4qF/

Sign up to request clarification or add additional context in comments.

2 Comments

If you want more then one variable just separate them with semicolon ';'
Tip for the uninitiated... depending upon your template structure, you can end up with all records showing only the last value of your variable (in my case, Angular updated the substitutions on a subsequent digest cycle, since they're all bound to the same expression)! To combat this situation, you could assign the variable as a property of the current record being iterated on (if practical to your use case). In the above example, this would become ng-init="day.f = forecast[day.iso]"
40

It's not the best answer, but its also an option: since you can concatenate multiple expressions, but just the last one is rendered, you can finish your expression with "" and your variable will be hidden.

So, you could define the variable with:

{{f = forecast[day.iso]; ""}}

6 Comments

Is this a documented feature?
@DanielF, I couldn't find. I just saw this comment, tested the idea, liked it and decided to add as an answer since it has more visibility and is harder to lose.
@DanielF, just found this high voted answer that proposes the same solution. It's also without a doc link.
@DanielF, I've updated my answer. I had to ask a question to understand it better. It's not a special feature. Just the behavior of concatenating expressions.
This hack is especially useful when you want the expression to be bound to scope changes, rather than run once on init.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.