首页 文章

ng-repeat:访问对象数组中每个对象的键和值

提问于
浏览
57

我有一个对象数组,我使用 ng-repeat 迭代它们,这很容易 . 该数组看起来像这样:

$scope.steps = [
    {companyName: true},
    {businessType: true},
    {physicalAddress: true}
];

我的 ng-repeat 属性看起来像:

<div ng-repeat="step in steps"> ... </div>

在每次迭代中, step 等于其中一个对象,如预期的那样 . 无论如何都要访问 step 对象的键和值?所以我可以这样做:

<div ng-repeat="(stepName, isComplete) in steps"> ... </div>

stepName == 'companyName'isComplete == true . 我已经尝试过做这件事但 stepName 总是最终成为step对象的索引(这很有意义) . 我只想弄清楚是否有另一种方法来编写 ng-repeat 语法,以便我可以获得密钥和值 .

感谢您的任何想法/建议 . 非常感激 .

PS . 我目前的工作是在我的控制器中执行此操作:

$scope.stepNames = [];
angular.forEach($scope.steps, function(isComplete, stepName){
     $scope.stepNames.push({stepName: stepName, isComplete: isComplete});
});

然后迭代它,但在视图中完成所有操作会很好

6 回答

  • 15

    转发器内的转发器

    <div ng-repeat="step in steps">
        <div ng-repeat="(key, value) in step">
            {{key}} : {{value}}
        </div>
    </div>
    
  • 103

    实际上,您的数据设计不佳 . 你最好使用类似的东西:

    $scope.steps = [
        {stepName: "companyName", isComplete: true},
        {stepName: "businessType", isComplete: true},
        {stepName: "physicalAddress", isComplete: true}
    ];
    

    然后很容易做你想要的:

    <div ng-repeat="step in steps">
     Step {{step.stepName}} status : {{step.isComplet}}
    </div>
    

    示例:http://jsfiddle.net/rX7ba/

  • 3

    如果这是您的选项,如果您将数据放入对象形式,它的工作方式我认为您希望:

    $scope.steps = {
     companyName: true,
     businessType: true,
     physicalAddress: true
    };
    

    这是一个小提琴:http://jsfiddle.net/zMjVp/

  • 7

    我认为问题在于您设计数据的方式 . 就语义而言,对我来说,它没有意义 . 究竟是什么步骤?

    Does it store the information of one company?

    如果是这样的话,步骤应该是一个对象(参见KayakDave的答案),每个“步骤”应该是一个对象属性 .

    Does it store the information of multiple companies?

    如果是这种情况,则步骤应该是一个对象数组 .

    $scope.steps=[{companyName: true, businessType: true},{companyName: false}]
    

    在任何一种情况下,您都可以轻松地使用一个(第二个案例为两个)ng-repeats迭代数据 .

  • 2

    这是另一种方式,无需嵌套中继器 .

    来自Angularjs docs

    可以使用以下语法使ngRepeat迭代对象的属性:

    <div ng-repeat="(key, value) in steps"> {{key}} : {{value}} </div>
    
  • -1

    似乎在Angular 1.3.12中你不再需要内部ng-repeat,外部循环返回集合的值是单个映射条目

相关问题