gpt4 book ai didi

javascript - Angular - 拼接函数总是删除最后一个元素

转载 作者:行者123 更新时间:2023-11-29 14:44:11 25 4
gpt4 key购买 nike

我有一个对象数组,我想在单击 Delete 键时删除某些对象。但是,无论我创建了多少行,它总是从行数组中删除最后一项。即使我明确地放入这样一行 $scope.rows.splice(1,1) - 它仍然会删除最后一个元素,而不是第二个。

JS

angular.module('app', ['ngAnimate', 'ui.bootstrap'])
.directive('queryBuilder', function() {
return {
restrict: 'E',
scope: {},
controller: function($scope) {
$scope.rows = [{}]

$scope.$on('addRowRqst', function(evt) {
// evt.stopPropagation()
$scope.rows.push({})
});
$scope.$on('removeRowRqst', function(evt, args) {
// evt.stopPropagation()
//THIS IS WHERE THE REMOVE HAPPENS
$scope.rows.splice($scope.rows.indexOf(args),1);
});
},
templateUrl: 'queryBuilderTemplate.html',
}
}).directive('queryRow', function() {
return {
scope: {},
restrict: 'EA',
templateUrl: 'queryRowTemplate.html',
controller: function($scope) {
$scope.addRqst = function() {
$scope.$emit('addRowRqst')
};
$scope.removeRqst = function(index) {
$scope.$emit('removeRowRqst', index)
};
},
link: function(scope, elem, attrs) {

}
}
});

相关的 HTML 片段

....
<button class="btn btn-default" ng-click="removeRqst($parent.row)" type="submit">Delete Row</button>
....

笨蛋: http://plnkr.co/edit/rDkXpIgiOSoNvLNPsVbP

测试:点击 Add Row 3 次。然后点击第二行的删除。您会看到它实际上删除了第 3 行,而不是第 2 行

最佳答案

为了清楚@ZsoltGyöngyösi 给出的答案:

Every element with and id field needs ng-model="$parent.row.field"

因此,如果您这样设置 queryRowTemplate.hml,正确的行将被删除:

queryRowTemplate.html

<div class="form-group col-md-3">
<label for="selectedField">Select Field</label>
<select id="selectedField" class="form-control" ng-model="$parent.row.field">
<option>title</option>
<option>application</option>
<option>subject</option>
<option>filetype</option>
</select>
</div>
<div class="form-group col-md-3">
<label for="logicalOperator">Logical Operator</label>
<select id="logicalOperator" class="form-control" ng-model="$parent.row.logical">
<option>equal to</option>
<option>not equal to</option>
</select>
</div>
<div class="form-group col-md-3">
<label for="searchText">Search</label>
<input id="searchText" class="form-control" type="text" placeholder="search..." ng-model="$parent.row.search" />
</div>
<div class="form-group col-md-3">
<label for="operator">Operator (optional)</label>
<select id="operator" class="form-control" ng-model="$parent.row.operator">
<option value=""></option>
<option>AND</option>
<option>OR</option>
</select>
</div>
<button class="btn btn-default" ng-click="addRqst()" type="submit">Add Row</button>
<button class="btn btn-default" ng-click="removeRqst($parent.row)" type="submit">Delete Row</button>
{{$parent.$index}}
<hr />

See Plunkr, here

关于javascript - Angular - 拼接函数总是删除最后一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34637512/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com