在我的页面上,我有一个动态的音乐人(玩家)列表,而玩家可以被移除并添加到列表中。每个玩家应该有多个乐器,这也是一个动态列表,而乐器可以从玩家的乐器列表中添加或删除。所以我们讨论的是两个嵌套的动态列表。
下面是代码和问题描述。
jamorg.html:
<!DOCTYPE html>
<html ng-app='jamorgApp'>
<head>
<link rel="stylesheet" type="text/css" href="C:\Users\jazzblue\Documents\Bootstrap\bootstrap-3.3.2-dist\css\bootstrap.min.css" />
<title>Jam Organizer</title>
</head>
<body>
<div ng-controller='JamOrgController as jamOrg'>
<h1>Jam</h1>
<div ng-repeat='player in players'>
<div>
<h3 style="display: inline-block;">player {{$index}}</h3>
<button ng-click="removePlayer($index)">Remove</button>
</div>
<br/>
<div ng-controller='JamOrgPlayerController as jamOrgPlayer'>
<div ng-repeat='instrument in player'>
<span>Instrument: {{instrument.instrument}},</span>
<span>Level: {{instrument.level}}</span>
<button ng-click="remove($index)">Remove</button>
</div>
<button ng-click="addInstrument()">Add Instrument</button>
Instrument: <input ng-model='newInstrument.instrument'>
Level: <input ng-model='newPlayer.level'>
</div>
</div>
</div>
<script type="text/javascript" src="C:\Users\jazzblue\Documents\AngularJS\angular.min.js"></script>
<script type="text/javascript" src="jamorgApp.js"></script>
</body>
</html>
jamorgApp.js
var app = angular.module('jamorgApp', []);
app.controller('JamOrgController', ['$scope', function($scope){
$scope.players = players;
$scope.removePlayer = function(index) {
$scope.players.splice(index, 1);
}
}]);
app.controller('JamOrgPlayerController', ['$scope', function($scope){
$scope.newInstrument = newInstrument;
$scope.remove = function(index) {
$scope.player.splice(index, 1);
}
$scope.addInstrument = function() {
$scope.player.push(newInstrument);
}
}]);
var players = [
[{instrument: 'Guitar', level: 3}, {instrument: 'Keyboard', level: 3}],
[{instrument: 'Bass', level: 4}],
[{instrument: 'Drums', level: 3}]
];
var newInstrument = [
{instrument: 'x', level: 'y'}
]
这是我的问题:同样的 newInstrument 被添加到所有不同的玩家列表中是错误的:每个玩家的乐器列表都应该有自己的 newInstrument
如何更改它以获得正确的设计? 谢谢!
答案 0 :(得分:2)
你在哪里:
$scope.addInstrument = function() {
$scope.player.push(newInstrument);
}
尝试做:
$scope.addInstrument = function() {
$scope.player.push(angular.copy(newInstrument));
}
更新
在您的HTML中:
<button ng-click="addInstrument(player)">Add Instrument</button>
在你的JS中:
$scope.addInstrument = function(player) {
player.push(angular.copy(newInstrument));
}
更新
我创建了一个fiddle,您可以在其中检查对代码的一些可能修改。它只使用一个控制器并修复了重复的对象问题。
答案 1 :(得分:1)
<button ng-click="addInstrument($index)">Add Instrument</button>
Instrument: <input ng-model='newInstrument.instrument'>
Level: <input ng-model='newPlayer.level'>
并且您的addInstrument
函数应该是这样的
$scope.addInstrument = function(index) {
$scope.players[index].push($scope.newInstrument);
}