使用AngularJs读取复杂对象

时间:2013-06-12 08:34:34

标签: angularjs

function ListServers($scope) {
    $scope.count = function() {
        return Object.keys(this.response.servers).length;
    };
    $scope.response={
        "status":true,
        "servers": {
            "vegas.domain.org": {
                "nickname":"Vegas VPS",
                "active":true,
                "frequency":5,
                "testers":['vegas','new-york'],
                "ports":{
                    "http":80,
                    "https":443
                }
            },
            "gains.domain.com": {
                "nickname": "Gains Shared Server",
                "active":false,
                "frequency":15,
                "testers":['vegas'],
                "ports":{
                    "http":80
                }
            }
        }
    };
}

这是我的JS。包括Angular JS之后我的HTML部分是这样的:

<div ng-app>
    <h1>Test Page</h1>
    <div ng-controller="ListServers">
        <span>Success? {{response.status}}</span><br/>
        <span>{{count()}} servers found:</span>
        <ol>
            <li ng-repeat='server in response.servers'>
                <strong>Nickname: </strong>{{server.nickname}}<br/>
                <strong>Is Active: </strong>{{server.active}}<br/>
                <strong>Freuency: </strong>{{server.frequency}} seconds<br/>
                <strong>Tests From: </strong>
                <ul>
                    <li ng-repeat='tester in server.testers'>
                        {{tester}}
                    </li>
                </ul>
                <strong>Ports: </strong>
                <ul>
                    <li ng-repeat='port in server.ports'>
                        {{port}}
                    </li>
                </ul>
                <br/>
            </li>
        </ol>
    </div>
</div>

此处<li ng-repeat='server in response.servers'>我可以阅读server.nicknameserver.frequency等的值。但我无法读取server本身的值。我期待值 vegas.domain.org gains.domain.com

那么如何检索值?

1 个答案:

答案 0 :(得分:1)

使用ng-repeat="(key, value) in expression"迭代对象的键和值:

<li ng-repeat="(domain, server) in response.servers">
  <strong>Domain: </strong>{{domain}}<br/>
  <strong>Nickname: </strong>{{server.nickname}}<br/>
  ...
</li>