2013-06-12 78 views
0
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。包括角JS後我的HTML部分是這樣的:使用AngularJs讀取複雜對象

<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.nickname讀取數值,server.frequency等,但我不能夠讀取值server本身。我期待值vegas.domain.orggains.domain.com

那麼如何檢索值?

回答

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> 
+0

這很簡單,整潔,完善。謝謝哥們 :) –