Daniel F Daniel F - 7 days ago 5
Javascript Question

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

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>

Answer

Use ngInit: http://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/

Comments