2016-04-14 34 views
0

我有ng-repeat表更新表:角 - 如何用新值

<table> 
    <tr> 
    <thead> 
     <th>key</th> 
     <th>value</th> 
    </thead> 
    </tr> 
    <tbody ng-repeat = "i in data"> 
    <td>{{i.key}}</td> 
    <td>{{i.value}}</td> 
</tbody> 
</table> 

table填充了data-ng-init,當一個用戶點擊按鈕:

<button ng-click="getNewVals()">new values</button> 

我得到json與新key-value,我的問題是如何重新填充key新價值baes的表?有沒有一個角度來做呢?

+0

顯示您的javascript請你,你犯了一個錯字,你寫ng-reapet而不是ng-repeat。 – Walfrat

+0

是的,這只是一個錯字,我的js的哪一部分? –

+0

控制器。 – Walfrat

回答

2

ng-repeat必將你迭代模型。如果您更新模型,ng-repeat將重新繪製。在您的示例中,每當$scope.data更改時,ng-repeat將自行更新。

+0

嘗試併發布結果。 –

2

使用這種方式。如果你提供你的JSON,這很好。

<table> 
 
    <tr> 
 
    <thead> 
 
     <th>key</th> 
 
     <th>value</th> 
 
    </thead> 
 
    </tr> 
 
    <tbody> 
 
    <tr ng-repeat = "(key, val) in data"> 
 
    <td>{{key}}</td> 
 
    <td>{{val}}</td> 
 
</tr> 
 
</tbody> 
 
</table>

1

你寫ng-reapet而不是ng-repeat

試試這個。

<table> 
    <tr> 
    <thead> 
     <th>key</th> 
     <th>value</th> 
    </thead> 
    </tr> 
    <tbody ng-repeat = "i in data"> 
    <td>{{i.key}}</td> 
    <td>{{i.value}}</td> 
</tbody> 
</table> 

<button ng-click="data.push({'key':1,'value':2})">new values</button> 
+0

但是如果密鑰已經在表中? –

+0

您正在編寫** ng-reapet **而不是** ng-repeat ** – 2016-04-14 12:03:07

+0

只是一個錯字,而不是代碼中的錯誤。 –

2

請看下面的例子:

<html> 
<head> 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js"></script> 
</head> 
<body ng-app="myApp" ng-controller="myCtrl"> 
    <ul> 
     <li ng-repeat="x in persons">{{x.name}}, {{x.age}}</li> 
    </ul> 
    <button ng-click="changeIt()">Change json</button> 
<script> 
    //1 module declaration 
    var app = angular.module('myApp', []); 
    //2 controller declaration 
    app.controller('myCtrl',function($scope){ 
     $scope.persons = [ 
      {name:"Peter", "age": 23}, 
      {name:"Lina","age":26}, 
      {name:"Robert", "age":33} 
     ]; 
     $scope.changeIt = function(){ 
      $scope.persons = [ 
       {name:"Larry",age: 59}, 
       {name:"Joseph", age: 63}, 
       {name:"Clara", age:71} 
      ]; 
     } 
    }); 
</script> 
</body> 
</html> 

希望它可以解決您的問題。