【发布时间】:2016-01-05 20:30:10
【问题描述】:
我有以下两个指令。一个是查询生成器,另一个是查询行。查询生成器指令使用 ng repeat 列出数组中的查询行。添加按钮有效,但我想包括一个删除按钮。但是,问题是我似乎无法获得 $index 以便我可以将它作为参数传递给删除函数(即 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 作为参数传递时,这里的 $index 是“未定义”
<button class="btn btn-default" ng-click="deleteRqst($index)" type="submit">Delete Row</button>
这里是笨蛋 http://plnkr.co/edit/rDkXpIgiOSoNvLNPsVbP
我的目标:让删除按钮起作用并删除选定的行
【问题讨论】:
-
我不确定为什么这不起作用,但您不需要通过 $index 包含轨道。 ng-repeat 自动创建 $index ,它在重复内可用
标签: javascript angularjs angularjs-directive angularjs-scope angularjs-ng-repeat