Himmators
Himmators

Reputation: 15036

How to output array of objects in angularjs?

I have an object that looks like this:

$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
]

I would lie to put out the name in a template within a foreach, and I would like to be able to reference the key.

<a  ng-href="#/{{location}}" class="location" ng-repeat="location in locations">{{location}}</a>

I can change the array around to look some other way, but I would like to keep it as an array so I can sort it and select items from the objects keys somehow. How should structure my array?

Upvotes: 0

Views: 77

Answers (2)

Ed_
Ed_

Reputation: 19138

I have to be honest, I really dislike the way you have structured your object. The object should be anonymous, and name should be a property within it. That way, you could use location.name.

All that being said, you can use Object.keys() to get an array of the keys within the object.

<a ng-href="getKey(location)" 
   class="location" 
   ng-repeat="location in locations"> {{ getKey(location) }}
</a>

getKey would have to be a function on your scope:

 $scope.getKey = function(location){
    return Object.keys(location)[0];
 }

Example plunk

Note: depending on desired browser support you might be better to iterate over the properties using a for (key in location) loop as some older browsers won't support Object.keys().

Upvotes: 1

mainguy
mainguy

Reputation: 8331

I think you want to wrap this in two repeats:

  <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>

Maybe check this Plunker

Upvotes: 1

Related Questions