Angularjs 如何在函数中使用每个ng重复项
我有一个小程序来添加和删除房间,增加和减少每个房间中的儿童数量。我还想设定房间里每个孩子的年龄。我面临的问题是如何在ng repeat中绑定ng模型名称。我的代码请看下面的提琴 感谢您的帮助您只需将“房间”传递给函数,并将相关数据存储在该房间中即可。变量Angularjs 如何在函数中使用每个ng重复项,angularjs,Angularjs,我有一个小程序来添加和删除房间,增加和减少每个房间中的儿童数量。我还想设定房间里每个孩子的年龄。我面临的问题是如何在ng repeat中绑定ng模型名称。我的代码请看下面的提琴 感谢您的帮助您只需将“房间”传递给函数,并将相关数据存储在该房间中即可。变量$index也可在循环中使用,可能很有用 <input name="" type="button" value="+" ng-click="addChildren(room)" /> <input name="child" t
$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)" />
但是,我现在还不想睡觉,所以这里有一个我如何处理您的项目的快速示例:
<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>
谢谢你的回复。
$scope.roomList = [
{count: 1}
];
$scope.addChildren = function(room){
++room.count;
};
$scope.removeChildren = function(room){
--room.count;
};
<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>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.rooms = [
{
children: [
{name: 'Jack', age: 7}
]
}
];
$scope.addRoom = function() {
$scope.rooms.push({children: []});
};
});