【发布时间】:2016-01-07 00:31:14
【问题描述】:
我有一个对象数组,我想在单击 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的相关sn-p
....
<button class="btn btn-default" ng-click="removeRqst($parent.row)" type="submit">Delete Row</button>
....
Plunker: http://plnkr.co/edit/rDkXpIgiOSoNvLNPsVbP
测试:点击 Add Row 3 次。然后点击第二行的删除。您会看到它实际上删除了第 3 行,而不是第 2 行
【问题讨论】:
-
您的 plunker 似乎工作正常。你如何检查哪个项目被删除?请注意,您没有将输入绑定到对象。
-
见我上面的测试评论。问题不在于消除。问题是删除正确的
-
Plunker 更清楚:plnkr.co/edit/IZN3XJMpJMyhrw1sEgOk 它工作正常。
-
总是删除最后行
-
对,我不希望它总是删除最后一行。我希望它删除我单击删除按钮的特定行
标签: javascript angularjs angularjs-directive