我正在动态添加输入,但是一旦我尝试在一个元素中添加一个输入,就会在第二个元素中添加相同的输入,该元素是由于 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>
Controller
$scope.choices = [];
$scope.operations = [{
hola: 'HELLO'
}, {
hola: 'BYE'
}
];
$scope.addNewChoice = function() {
$scope.choices.push(['']);
};
当您单击添加字段
按钮时,它应该只在正确的框/表单中添加一个输入,而不是在两个框中添加。
我没有很好地解释自己,但这里我有一个 JSBin所以你可以检查我的问题。
最佳答案
稍微不同的方式,你也可以尝试一下
<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(['']);
};
});
关于javascript - 动态输入,避免在不同元素上重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30657568/