我有一个小程序来添加和删除房间,并增加和减少每个房间的儿童数量。另外我想设置每个孩子在房间里的年龄。我正面临着如何在ng-repeat中绑定ng-model名称的问题。请参阅以下小提琴我的代码
$scope.incrementRoomCount = function(){
count = count+1;
$scope.roomList.push({roomCount:count});
}
$scope.addChildren = function(){
childrenCount = childrenCount+1;
this.noOfChildren = childrenCount;
$scope.childAgeContainer = true;
}
感谢您的帮助
答案 0 :(得分: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: []});
};
});