2016-03-05 70 views
1

這已被問了幾次,但它似乎仍然不起作用。我有一個非常基本的例子。我沒有在瀏覽器中運行index.html文件,我在服務器上運行它。ng-repeat在模板不起作用的角度指令

的index.html

<div ng-view> </div> 


    <div ng-controller="Controller"> 
     <my-names listcustomers='customer'></my-names> 
    </div> 

模板:

<div ng-repeat="listcustomers"> 

     <table class="box-table" width="100%"> 

      <thead> 
      <tr> 
       <th>Name: {{listcustomers.name}}</th> 
       <th>Age: {{listcustomers.age}}</th> 
      </tr> 
      </thead> 
     </table> 

    </div> 

控制器

angular.module('myApp'). 
controller("Controller",["$scope", function($scope){ 

    $scope.customer = [ 

     { 
      name: 'Drew', 
      age: 30 
     }, 

     { 
      name: 'Meike', 
      age: 54 
     }, 

     { 
      name: 'Peter', 
      age: 25 
     } 
    ]; 

}]) 
    .directive("myNames",function($scope){ 
     return{ 
      restrict : 'E', 
      transclude : false, 
      templateUrl: 'pages/myNames.html', 
      scope: { 
       listcustomers: "=" 
      } 
     }; 
    }); 
+0

NG重複=「客戶在listcustomers」,然後參考customer.name –

+0

@KobiCohen當我這樣做,我得到一個錯誤說angular.js:12722錯誤:[$注入器:unpr]未知的提供者:$ scopeProvider < - $ scope < - myNamesDirective – Drew1208

+0

@KobiCohen得到它的工作,不得不從指令函數中刪除$範圍。 – Drew1208

回答

2

您需要定義將在ng-repeat主體中使用的變量。所以listcustomers是一個對象數組,你需要迭代數組中的每個元素。試着在你的模板如下:

<div ng-repeat="customer in listcustomers"> 
    <table class="box-table" width="100%"> 
     <thead> 
     <tr> 
      <th>Name: {{customer.name}}</th> 
      <th>Age: {{customer.age}}</th> 
     </tr> 
     </thead> 
    </table> 
</div> 
1

使用關鍵字進行迭代使用ng-repeat爲:

<div ng-repeat="customer in listcustomers"> 
    <table class="box-table" width="100%"> 
    <thead> 
    <tr> 
     <th>Name: {{customer.name}}</th> 
     <th>Age: {{customer.age}}</th> 
    </tr> 
    </thead> 
    </table> 
</div>