Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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> 
like image 836
Daniel F Avatar asked May 21 '13 08:05

Daniel F


People also ask

How to use variables in Angular template?

In the template, you use the hash symbol, # , to declare a template variable. The following template variable, #phone , declares a phone variable with the <input> element as its value. Refer to a template variable anywhere in the component's template.

How to declare variable in Angular?

You can declare variables in html code by using a template element in Angular 2 or ng-template in Angular 4+. Templates have a context object whose properties can be assigned to variables using let binding syntax. Note that you must specify an outlet for the template, but it can be a reference to itself.

What is template reference variable?

A template reference variable is often a reference to a DOM element within a template. It can also be a reference to an Angular component or directive or a web component (Read more at Angular.io). That means you can easily access the variable anywhere in the template.

What are templates in AngularJS?

Templates in AngularJS are simply an HTML file filled or enriched with AngularJS stuff like attributes and directives. A directive is a marker element that is used to target a particular attribute or class to render its behavior as according to the needs.


1 Answers

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/

like image 114
coma Avatar answered Oct 15 '22 04:10

coma