简体   繁体   English

AngularJS ng-repeat:遍历特殊对象字段

[英]Angularjs ng-repeat: iterate over a special object fields

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? 是否可以遍历ng-repeat中对象的字段? Eg 例如

<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. 提前致谢。

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. 可以猜到, k是键, v是键的值。

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. 这是使用ng-if并遍历对象的解决方案。 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. 但是正如我提到的那样,javascript不会按顺序遍历对象,因此最好的选择是对数组中的属性进行重新排序,然后再次进行遍历。 This below iterate as NAME_1, NAME_2, TEXT_1, TEXT_2 下面的内容以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;
    }
  }

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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