ANGULARJS ng-repeat - 使用对象['propertyname']进行迭代

时间:2015-03-23 08:16:25

标签: javascript angularjs

如何使用属性名称(例如

)重复对象
$scope.myobjects = [
{
    'property1': {
        id: 0,
        name: 'somebody'
    }
}, 
{
    'property2': {
        id: 1,
        name: 'someguy'
    }
}];

3 个答案:

答案 0 :(得分:0)

由于对象的键不相同,所以不能只迭代它。也许你可以这样做:

<强> DEMO

<div ng-repeat="object in myobjects">{{getValue(object,'id') }}
  {{getValue(object,'name')}}
</div>

在您的控制器中:

 $scope.getValue = function(value,field) {
    var key = Object.keys(value).filter(function(val) 
    {
      return val != "$$hashKey"
    })[0];
   return value[key][field];
  }

答案 1 :(得分:0)

如果你想获取对象的属性名称(第二个是循环到对象中),你必须像下面一样添加一个嵌套的ng-repeat:

<div ng-repeat="(index, object) in myobjects">
  <div ng-repeat="(key, value) in object">
    <strong>key: </strong> {{ key }}, <strong>value: </strong>{{ value }}
    <strong>value.id: </strong> {{ value.id }}, <strong>value.name: </strong>{{ value.name }}
  </div>
</div>

打印:

密钥: property1,值: {&#34; id&#34;:0,&#34;名称&#34;:&#34;某人&# 34;} value.id: 0, value.name:某人

键: property2,值: {&#34; id&#34;:1,&#34;名称&#34;:&#34; someguy&# 34;} value.id: 1, value.name: someguy

演示:http://embed.plnkr.co/SIMjaXMZPzbHLOCYRU8T/preview

答案 2 :(得分:0)

ng-repeat with obj prop

<div ng-app="demo" ng-controller="abc">
    <div ng-repeat="(key, value) in myobjects">
        <div ng-repeat="objProp in value">{{objProp.name}}</div>
    </div>
</div>

var app = angular.module('demo', []);
app.controller('abc', function ($scope) {
    $scope.myobjects = [{
        'property1': {
            id: 0,
            name: 'somebody'
        }
    }, {
        'property2': {
            id: 1,
            name: 'someguy'
        }
    }];
})

此处正常工作 jsfiddle