简体   繁体   中英

Can someone explain Angular as-for-in expression notation?

In Angular loops (ng-repeat, ng-options) you can use the following syntax:

item as item.label for item in items

Can someone please explain what each of the tokens in the expression is doing there and what it means? Can you point me to the documentation of this? I can't figure out what to search for (searching for 'as' or 'for' is useless). It is not mentioned in the documentation for ng-repeat or ng-options.

I know that somehow it lets you pick an object from a list of objects, but 'item' appears in the expression twice and it is not clear to me what the role of that token is in this expression.

Sorry if this is all documented some place which I can not find....

You have an array "items". And you are interating through it with

item in items

As the example you have copied incompletely from this page " https://docs.angularjs.org/api/ng/directive/ngOptions " would normally create a dropdown, there would be now the problem that the "item" object you currently have in your iteration has more fields than just a string to show as label for your dropdown entry. Here is the object again:

$scope.items = [{
  id: 1,
  label: 'aLabel',
  subItem: { name: 'aSubItem' }
}, {
  id: 2,
  label: 'bLabel',
  subItem: { name: 'bSubItem' }
}];

So what do you want to show then? Yeah, you want to show "item.label". And thats what

item as item.label

does. It tells the loop to use the current "item.label" value as "item" for this specific loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM