AngularJS: How to set a variable inside of a template?

JavascriptAngularjsNg Init

Javascript Problem Overview


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>

Javascript Solutions


Solution 1 - Javascript

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/

Solution 2 - Javascript

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]; ""}}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDaniel FView Question on Stackoverflow
Solution 1 - JavascriptcomaView Answer on Stackoverflow
Solution 2 - JavascriptZanonView Answer on Stackoverflow