ng-repeat循环遍历对象中的对象

时间:2014-07-03 16:47:13

标签: javascript angularjs loops angularjs-ng-repeat ng-repeat

我很困惑如何遍历这个数据模型。

$scope.object = [ {person1: {name: 'jon', height: 100}} , {person2: {name: 'joe', height: 200}}, {person3: {name: 'lisa', height: 150}}]

我正在尝试像这样的重复

<tr ng-repeat = "person in object[0]">
    <td>{{person.name}}</td>
</tr>

这当然只会显示'jon'。我怎样才能得到所有人(x).name?我可以将它们命名为all1而不是person1,person2,但我的项目的数据模型不允许这样。能做什么?

由于

2 个答案:

答案 0 :(得分:6)

将对象数据中缺少的大括号放在一边,你可以做一些愚蠢的事情,比如

<tr ng-repeat="person in object">
    <td ng-repeat="keys in person">
        {{keys.name}}
    </td>   
</tr>

...这会做你想要的(内部ng-repeat只会循环一次,因为每个&#34; person&#34;只有一个键(&#34; person1&#34;,&# 34; person2&#34; ...)但更好的解决方案可能是更改您的数据结构,以删除那些不必要的person1,person2等标识符并将其视为数组:

$scope.object = [
    {name:'Joe'},
    {name:'Susan'}
];

或删除数组括号并将其视为哈希表:

$scope.object = {
    person1: {name:'Bob'}, 
    person2: {name:'Ted'}
};

使用其中任何一种数据结构,您的HTML模板都是相同的:

<tr ng-repeat="person in object">
    <td>{{person.name}}</td>
</tr>

现在你正在尝试将它构建为一个数组和一个哈希,这没有任何好处,只会让访问数据更加笨拙。

答案 1 :(得分:4)

如果你的模型将在person1,person2,person3等中返回数据。 这是指令方式的答案。

下面是HTML

<div ng-controller="MyCtrl">
   <div ng-repeat = "person in object">
      <div make-json> </div>
   </div>
</div>

这是我的控制器和指令

var app = angular.module('myApp', []);

function MyCtrl($scope) {
    $scope.object = [{
        person1: {
            name: 'jon',
            height: 100
        }
    }, {
        person2: {
            name: 'joe',
            height: 200
        }
    }, {
        person3: {
            name: 'lisa',
            height: 150
        }
    }];
}

app.directive('makeJson', function() {
    return {
        restrict: 'AEC',
        link: function(scope, elm, attrs) {
            var formattedText = "person";
            formattedText = formattedText + (parseInt(scope.$index) + 1);
            elm.text(scope.person[formattedText.toString()].name);
        }
    };
});

希望这对你有用。感谢。

相关问题