AngularJS: 如何在模板中设置变量?

如何避免在第三行中使用 {{f = ...}}语句打印出 forecast[day.iso]的内容?

我想避免在每次迭代中使用 forecast[day.iso].temperature等等。

<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>
105433 次浏览

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/

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