2014-01-28 33 views
0

我有一個小程序來添加和刪除房間並增加和減少每個房間中的兒童數量。我也想設定每個孩子在房間裏的年齡。我正面臨着如何在ng-repeat內綁定ng-model名稱的問題。請參閱下面搗鼓我的代碼如何在函數中使用每個ng-repeat項目

http://jsfiddle.net/ab23r/6/

$scope.incrementRoomCount = function(){ 
     count = count+1; 
     $scope.roomList.push({roomCount:count}); 
    } 
    $scope.addChildren = function(){ 
     childrenCount = childrenCount+1; 
     this.noOfChildren = childrenCount; 
     $scope.childAgeContainer = true; 
    } 

感謝所有幫助

+0

感謝您的回覆。 – Lara

回答

0

你只需要在那個房間裏通過「房」的功能和存儲相關數據。變量$index也可在循環中使用,並且可能有用。

<input name="" type="button" value="+" ng-click="addChildren(room)" /> 
<input name="child" type="text" style="text-align:center;" ng-model="room.count" /> 
<input name="" type="button" value="-" ng-click="removeChildren(room)" /> 

的JavaScript:

$scope.roomList = [ 
    {count: 1} 
]; 
$scope.addChildren = function(room){ 
    ++room.count; 
}; 
$scope.removeChildren = function(room){ 
    --room.count; 
}; 

但是,我不喜歡睡覺,只是還沒有,所以這裏有一個如何我可能會接近你的項目一個簡單的例子:Live demo (click).

<div ng-app="myApp" ng-controller="myCtrl"> 

    <form> 
    <button ng-click="addRoom()">Add Room</button> 
    <div ng-repeat="room in rooms"> 
     <hr> 
     <h2>Room {{$index+1}}</h2> 
     <p>Child count: {{room.children.length}}</p> 
     <button ng-click="room.tempChild={}">Add Child</button> 
     <div ng-show="room.tempChild"> 
     <input type="text" placeholder="Child's Name" ng-model="room.tempChild.name"> 
     <input type="number" placeholder="Child's Age" ng-model="room.tempChild.age"> 
     <button ng-click="room.children.push(room.tempChild); room.tempChild=false">Submit</button> 
     <button ng-click="room.tempChild=false">Cancel</button> 
     </div> 
     <h3>Children:</h3> 
     <div ng-repeat="child in room.children"> 
     <span>Name: {{child.name}} Age: {{child.age}}</span><button ng-click="room.children.splice($index, 1)">x</button> 
     </div> 
    </div> 
    </form> 

</div> 

JavaScript:

var app = angular.module('myApp', []); 

app.controller('myCtrl', function($scope) { 

    $scope.rooms = [ 
    { 
     children: [ 
     {name: 'Jack', age: 7} 
     ] 
    } 
    ]; 
    $scope.addRoom = function() { 
    $scope.rooms.push({children: []}); 
    }; 

}); 
相關問題