2014-07-16 51 views
0

我正在使用ng-repeat來創建一個項目(列表)的數組,我想每個項目都有一個id作爲它在數組中的位置。AngularJS - ng-repeat - 如何用ID創建一個數組

JS FIDDLE DEMO的位置:http://jsfiddle.net/m62Ez/15/

請看看下面,看起來像ng-model="item.id"從未分配。任何建議非常感謝。

HTML

<div ng-controller="MainCtrl"> 
    <button ng-click="addItem()">Add Item</button> 

    <ul> 
     <li ng-repeat="item in items"> 
      <input type="hidden" ng-model="item.id" ng-value="{{$index}}" /> 
      <input type="text" ng-model="item.name" /> 
     </li> 
    </ul> 
    <hr /> 
    <button ng-click="saveAll()">Save All</button> 
</div> 

JS

var app = angular.module("app", []); 
app.controller("MainCtrl", function ($scope) { 

    $scope.items = []; 
    $scope.addItem = function() { 
     $scope.items.push({}); 
    } 
    $scope.saveAll = function() { 
     console.log($scope.items); // item's do not have id's 
    } 

}); 

回答

2

的隱藏字段是沒有用的。如果你希望你的對象有一個ID,然後用一個ID生成它們:

$scope.addItem = function() { 
    $scope.items.push({id: $scope.items.length}); 
} 

更新的jsfiddle:http://jsfiddle.net/K7DgE/