2016-03-05 86 views
0

我正在尝试向数组中动态添加和赋值,并让它们填充。但是我甚至无法打印一个console.log语句。我有点困惑,为什么我没有收到错误或console.log语句。动态地将名称添加到模板中的数组

控制器:

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

    $scope.customer = [ 

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

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

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

    $scope.addCustomer = function(customer_name,customer_age){ 

     var person = { 
      name: customer_name, 
      age: customer_age 
     }; 

     customer.add(person); 

     console.log("You added a person "+person.name+" who is "+person.age+" years old."); 
    } 

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

模板:

<div ng-repeat="customer in listcustomers"> 

    <table class="box-table" width="100%"> 
     <tr> 
      <th>Name:{{customer.name}}</th> 
      <th>Age:{{customer.age}}</th> 
     </tr> 
    </table> 

</div> 

<div> 
    <input type="text" placeholder="enter a name" ng-model="customer_name"> 
    <input type="text" placeholder="enter a age" ng-model="customer_age"> 
    <button type="submit" value="Submit" ng-click="addCustomer(customer_name,customer_age)">Submit</button> 
</div> 

的index.html

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

回答

0

你应该通过addCustomer函数模板这样

<div ng-controller="Controller"> 
     <my-names listcustomers='customer' add-customer='addCustomer'></my-names> 
</div> 
+0

对不起,没有工作。出于某种原因,ng-click没有响应。 – Drew1208

+0

对不起,有一个错字。尝试'add-customer'而不是'addCustomer'。看到我更新的答案。 – 2016-03-05 21:11:22

+0

什么都没有。我甚至试图从ng-click中删除这些变量,因为intellij告诉我“未解决的变量”,而且这似乎没有做任何事情。 – Drew1208

相关问题