javascript - AngularJS:如何在 HTML 中显示具有两个 ng-repeats 的深层对象值

标签 javascript angularjs

我想从 JSON 对象访问属性。对象是

$scope.people = [
    {
        "name": "Adam",
        "age": "21",
        "places": {"town": "IL"},
        "work": "Manager"
    },
    {
        "name": "Christina",
        "age": "25",
        "places": {"town": "MS"},
        "work": "Designer"
    },
    {
        "name": "Luke",
        "age": "22", 
        "places": {"town": "VA"},
        "work": "Developer"
    }
]

$scope.heads = ["Name", "Age", "Work", "Town"]
$scope.attrs = ["name", "age", "work", "places.town"]

我想访问地方属性。这是我正在使用的 HTML:

<table>
<thead>
    <tr>
        <th ng-repeat="head in heads">{{ head }}</th>
    </tr>
</thead>
<tbody>
    <tr ng-repeat="person in people">
        <td ng-repeat="attr in attrs"> {{ person[attr] }} </td>
    </tr>
</tbody>

我想要实现的是:

Name        Age        Work          Town
-------------------------------------------------
Adam        21         Manager       IL
Christina   25         Designer      MS
Luke        22         Developer     VA

除了城镇领域外,一切都工作正常。

最佳答案

您无法从调用 person["places.town"] 的对象获取值。获取该值的正确方法是 person["places"]["town"]

所以我建议您在返回正确属性的范围内创建一个函数。示例:

$scope.getValue = function(persion, property) {

    if (property.indexOf('.') == -1) return person[property];

    var p = property.split('.');

    return person[p[0]][p[1]];

}

在 ng-repeat 中使用它,如下所示:

<td ng-repeat="attr in attrs"> {{ getValue(person, attr) }} </td>

您可以改进该功能,使其更加动态。

关于javascript - AngularJS:如何在 HTML 中显示具有两个 ng-repeats 的深层对象值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45274700/

相关文章:

java - 当参数很长时出现 411 Length required 错误

angularjs - 环境标志已弃用

Javascript 代码在我的网站上无法工作

javascript - Highcharts 不会在 Chrome 应用中显示

javascript - 如何从 Rails Controller 操作调用 javascript

javascript - 如何在 html 上制作 CSS 多列布局以在用户单击时在列之间移动

angularjs - 当 typeahead-editable 为 false 时设置输入无效

javascript - Angular ng-show 在简单的示例脚本中没有按预期工作

javascript - 为什么 ng-bind-html 只显示文本而不显示链接?

javascript - jquery 有更好的循环吗?