2016-03-05 69 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>