2017-03-06 64 views
0

我正在開發一個應用程序,其中的一部分應該列出javascript對象的人名。但是,它並沒有像我期望的那樣遍歷我的json,而是它將整個事物返回,就好像它是一個對象一樣。它爲什麼這樣做?Angular ng-repeat不會迭代通過json

破碎Plunker https://plnkr.co/edit/u9DHsTlaO0H2G2jqnzLa

的Index.html

<!DOCTYPE html> 
<html ng-app="plunker"> 
    <head> 
    <meta charset="utf-8" /> 
    <title>AngularJS Plunker</title> 
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.js"></script> 
    <script src="app.js"></script> 
    </head> 
    <body> 
    <people-list></people-list> 
    </body> 
</html> 

app.js

var app = angular.module("plunker", []); 
app.directive("peopleList", function() { 
    return { 
     restrict: "E", 
     templateUrl: "people-list.html", 
     controller: function() { 
     this.people = peopleObject; 
     }, 
     controllerAs: "people" 
    }; 
    }); 

    var peopleObject = [ 
    { firstname: 'John', 
      middlename: 'K', 
      lastname: 'Doe', 
      sex: "M" 
    }, 
     { 
     firstname: 'Jane', 
      middlename: 'R', 
      lastname: 'Doe', 
      sex: "F" 
    }, 
     { 
     firstname: 'Jacob', 
      middlename: 'Harold', 
      lastname: 'Smith', 
      sex: "M" 
     } 
    ]; 

人list.html

<ul class="list-group menuIcons"> 
    <li ng-click="tab.setTab(1);" class="list-group-item" ng-repeat="person in people"> 
     {{person.firstname}} 
    </li> 
</ul> 

回答

4

嘗試改變這一點。您在指令定義controllerAs,那麼你應該使用模板

<ul class="list-group menuIcons"> 
    <li ng-click="tab.setTab(1);" class="list-group-item" ng-repeat="person in people.people"> 
    {{person.firstname}} 
</li> 
</ul> 
+0

我可以問,爲什麼用戶在使用'this.'?當我試圖刪除它甚至沒有工作。爲什麼? – Smit

+0

這樣做,謝謝!我仍然不明白那些額外的「人」來自哪裏 – Mr404servererror

+1

@Smit用戶使用'controllerAs'語法。 –

0

你錯過了把controllerAS別名NG重複。

<ul class="list-group menuIcons"> 
    <li ng-click="tab.setTab(1);" class="list-group-item" ng-repeat="person in people.people"> 
     {{person.firstname}} 
    </li> 
</ul> 
0

人包含另一個對象的人,所以你需要person.person

使用像下面的代碼

<ul class="list-group menuIcons"> 
    <li ng-click="tab.setTab(1);" class="list-group-item" ng-repeat="person in people"> 
     {{person.firstname}} 
    </li> 
</ul> 

檢查工作plnkr

0

更改people-list.html

<ul class="list-group menuIcons"> 
    <li ng-click="tab.setTab(1);" class="list-group-item" ng-repeat="person in people.people"> 
     {{person.firstname}} 
     </li> 
</ul> 

您需要更改

ng-repeat="person in people"> 

ng-repeat="person in people.people">