Question

I have an object:

var options = {
    NAME_1 : "Name 1",
    TEXT_1 : "Description goes here",
    NAME_2 : "Name 2",
    TEXT_2 : "Description2 goes here",
};

Is it possible to iterate over the fields of the object inside the ng-repeat? E.g.

<div ng-repeat="item in options">
    <span class="title">{{item.name}}</span>
    <span class="text">{{item.text}}</span>
</div>

I will greatly appreciate any advice.

Thanks in advance.

Was it helpful?

Solution 2

this is not going to work as you imagine, perhaps your object can look like this,

var options = [
{
name : "Name 1",
text : "Description goes here"
},
{
name : "Name 2",
text : "Description2 goes here"
}
];

now you can iterate just as you want it.

Or, you can I guess iterate over all your values in the object but you need to keep in mind that these values are not really related to each other, besides just being in the same object.

This is the solution with ng-if and iterate over the object. But as I mentioned, javascript iterates over objects not in order so your best bet to reorder your properties in an array and then iterate again. This below iterate as NAME_1, NAME_2, TEXT_1, TEXT_2

app.controller('MainCtrl', function($scope) {
  var options = {
    NAME_1 : "Name 1",
    TEXT_1 : "Description goes here",
    NAME_2 : "Name 2",
    TEXT_2 : "Description2 goes here",
};
$scope.options = options;
$scope.check = function(title, key) {
   if(key.split('_')[0] === title) {
     return true;
   } 
}
});

<div ng-repeat="(k,v) in options|orderBy:k">
    <span ng-class="title" ng-if="check('NAME',k)">{{k}}</span>
    <span ng-class="text" ng-if="check('TEXT',k)">{{k}}</span>     
</div>

COMPLETE SOLUTION: If you also use underscore, you can do this.

<div ng-repeat="x in optionsArray">
      <span ng-class="title" ng-if="check('NAME',x)">{{x[1]}}</span>
      <span ng-class="text" ng-if="check('TEXT',x)">{{x[1]}}</span>
</div>

app.controller('MainCtrl', function($scope) {
  var options = {
    NAME_1: "Name 1",
    TEXT_1: "Description goes here",
    NAME_2: "Name 2",
    TEXT_2: "Description2 goes here",
  };
  $scope.options = options;
  $scope.optionsArray = _.pairs(options);
  $scope.check = function(title, key) {
    if (key[0].split('_')[0] === title) {
      return true;
    }
  }

});

OTHER TIPS

Absolutely! Use the following syntax:

<div ng-repeat="(k, v) in options">

As you can guess, k is the key and v is the value of the key.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top