我正在动态添加输入,但是一旦我尝试在元素中添加一个输入,就会在二手元素中添加相同的输入,这是因为ng-repeat而存在:
<div ng-repeat="operation in operations">
<p>{{operation.hola}}</p>
<button class="btn" ng-click="addNewChoice([])">Add fields</button>
<div data-ng-repeat="choice in choices track by $index">
<input type="text" ng-model="choice.text">
</div>
</div>
控制器
$scope.choices = [];
$scope.operations = [{
hola: 'HELLO'
}, {
hola: 'BYE'
}
];
$scope.addNewChoice = function() {
$scope.choices.push(['']);
};
当您点击Add Fields
按钮时,它应该只在正确的框/表格中添加一个输入,而不是在两个框中。
我没有很好地解释自己,但在这里我有一个JSBin所以你可以检查我的问题。
答案 0 :(得分:2)
稍微不同的方式,你也可以尝试这个
<div ng-repeat="operation in operations">
<div class="panel">
<div class="panel-body">
<p>{{operation.hola}}</p>
<button class="btn" ng-click="addNewChoice(operation)">Add fields</button>
<div data-ng-repeat="choice in choices[operation.hola] track by $index">
<input type="text" ng-model="choice.text">
</div>
</div>
</div>
</div>
JS
angular.module('ionicApp',[])
.controller('mainCtrl', function($scope) {
$scope.choices = {};
$scope.operations = [{
hola: 'HELLO'
}, {
hola: 'BYE'
}];
$scope.addNewChoice = function(operation) {
$scope.choices[operation.hola] = $scope.choices[operation.hola] || [];
$scope.choices[operation.hola].push(['']);
};
});
答案 1 :(得分:1)
如果您希望每个操作choices
不同,则需要创建2个不同的choices
数组。最好的方法是在每个操作上创建一个chioces
对象:
$scope.operations = [{
hola: 'HELLO',
choices: []
}, {
hola: 'BYE',
choices: []
}];
然后在你的HTML中:
<div ng-repeat="operation in operations">
<p>{{operation.hola}}</p>
<button class="btn" ng-click="operation.choices.push([])">Add fields</button>
<div data-ng-repeat="choice in operation.choices track by $index">
<input type="text" ng-model="choice.text">
</div>
</div>
编辑:如果由于某种原因不想修改操作数组,可以为选项创建一个二维参差不齐的数组:
$scope.operationChoices = [];
for (var i = 0; i < operations.length; ++i) {
$scope.operationChoices.push([]);
}
然后您的HTML将是:
<div ng-repeat="operation in operations" ng-init="choices = operationChoices[$index]">
<p>{{operation.hola}}</p>
<button class="btn" ng-click="choices.push([])">Add fields</button>
<div data-ng-repeat="choice in choices track by $index">
<input type="text" ng-model="choice.text">
</div>
</div>
答案 2 :(得分:1)
为什么不能修改json?它现在在你的程序中 - 你可以做任何事情。
我是这样做的:
$scope.operations = [{hola: 'HELLO'}, {hola: 'BYE'}];
// this is JS - you have the power :)
// call this right after you get the json from your ajax call or something
$scope.operations = preProcessOperations($scope.operations);
$scope.addNewChoice = function(choices) {
choices.push(['']);
};
function preProcessOperations(ops){
for(var i = 0; i < ops.length; i++){
ops[i].choices = [];
}
}
HTML:
<div ng-repeat="operation in operations">
<p>{{operation.hola}}</p>
<button class="btn" ng-click="addNewChoice(operation.choices)">Add fields</button>
<div data-ng-repeat="choice in operation.choices track by $index">
<input type="text" ng-model="choice.text">
</div>
</div>