gpt4 book ai didi

javascript - Angularjs ng 重复 - 按 $index 删除

转载 作者:行者123 更新时间:2023-11-30 16:21:50 25 4
gpt4 key购买 nike

我有以下两个指令。一个是查询生成器,另一个是查询行。查询生成器指令使用 ng repeat 列出数组中的查询行。添加按钮有效,但我想包含一个删除按钮。然而,问题是我似乎无法获得 $index 以便我可以将它作为参数传递给 delete 函数(即 delete($index))

下面是JS代码

  .directive('queryBuilder', function() {
return {
restrict: 'E',
scope: {},
controller: function($scope) {
$scope.rows = [{}]

//add method not used - delete in future
$scope.add = function() {
$scope.rows.push({})
}

$scope.$on('addRowRqst', function(evt) {
// evt.stopPropagation()
console.log('add rqst received')
$scope.rows.push({})
});
$scope.$on('deleteRowRqst', function(evt) {
// evt.stopPropagation()
console.log('delete rqst received')
$scope.rows.push({})
});
},
templateUrl: 'queryBuilderTemplate.html',
}
}).directive('queryRow', function() {
return {
scope: {},
restrict: 'EA',
templateUrl: 'queryRowTemplate.html',
controller: function($scope) {
$scope.addRqst = function() {
console.log('addRowRqst click')
$scope.$emit('addRowRqst')
};
$scope.deleteRqst = function(index) {
console.log('deleteRowRqst click')
$scope.$emit('deleteRowRqst')
};
},
link: function(scope, elem, attrs) {

}
}

这是查询生成器模板的 HTML 代码

<form role="form">
<query-row ng-repeat="row in rows track by $index"></query-row>
<button type="submit" class="btn btn-primary">Submit</button>
</form>

这里是删除按钮(查询行模板的一部分)。当我尝试将它作为参数传递时,这里的 $index 是“未定义的”

<button class="btn btn-default" ng-click="deleteRqst($index)" type="submit">Delete Row</button>

这是个笨蛋 http://plnkr.co/edit/rDkXpIgiOSoNvLNPsVbP

我的目标:让删除按钮起作用并删除选定的行

最佳答案

这是因为 $index 在父范围内,但您在查询行指令中使用了隔离范围。

尝试以下操作:

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

或者,删除隔离范围。

关于javascript - Angularjs ng 重复 - 按 $index 删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34620666/

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