我有一个看起来像这样的对象:
$scope.locations [
{Kanaanbadet: {"name":"Kanaanbadet","image":"http://www.stockholm.se/Web/Core/Pages/Special/StreamServiceGuideImage.aspx?path=%2fWeb%2fCore%2fPages%2fSpecial%2fServiceGuideFile.aspx%3ffileid%3d14b313cb2b2f45e380eb88156c95b539","_cached_page_id":"4b71e342c82be9de1c74de3c2f57ea1c4dde8150","long":"17.85448","lat":"59.34966","url":"http://www.stockholm.se/-/Serviceenhetsdetaljer/?enhet=cf0a856830e4422cb55dcd60e8e6b40b"}},
{Johannelundsbadet:{"name":"Johannelundsbadet","image":"http://www.stockholm.se/Web/Core/Pages/Special/StreamServiceGuideImage.aspx?path=%2fWeb%2fCore%2fPages%2fSpecial%2fServiceGuideFile.aspx%3ffileid%3d3e4c2056b5534cfc9b0799e2377b8ce4","_cached_page_id":"18cf34222d74612979afd945a925abc0bf16e44d","long":"17.98914","lat":"59.34098","url":"http://www.stockholm.se/-/Serviceenhetsdetaljer/?enhet=ebf8d49780224e908064551c35dbcca4"}},
...more items
]
我会撒谎在foreach的模板中输出名称,我希望能够引用密钥。
<a ng-href="#/{{location}}" class="location" ng-repeat="location in locations">{{location}}</a>
我可以改变数组以查看其他方式,但我想将其保留为数组,以便我可以对它进行排序并以某种方式从对象键中选择项目。应该如何构造我的数组?
答案 0 :(得分:1)
我想你想把它包装成两个重复:
<div ng-controller="DemoCtrl">
<div ng-repeat="location in locations">
<a ng-href="#/{{item.url}}" class="location" ng-repeat="item in location">{{item.name}}</a>
</div>
</div>
也许请查看此Plunker
答案 1 :(得分:1)
我必须诚实,我真的不喜欢你构建对象的方式。该对象应该是匿名的,name应该是其中的属性。这样,您就可以使用location.name
。
所有这些,您可以使用Object.keys()
来获取对象中的键数组。
<a ng-href="getKey(location)"
class="location"
ng-repeat="location in locations"> {{ getKey(location) }}
</a>
getKey
必须是您范围的功能:
$scope.getKey = function(location){
return Object.keys(location)[0];
}
注意:根据所需的浏览器支持,您可能最好使用for (key in location)
循环对属性进行迭代,因为某些较旧的浏览器won't support Object.keys()
。< / p>