Angularjs ng repeat - delete by $index

Angularjs ng repeat - delete by $index

本文关键字:by index delete ng repeat Angularjs      更新时间:2023-09-26

我有以下两个指令。一个是查询生成器,另一个是一个查询行。查询生成器指令使用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>

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

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

这是plunkerhttp://plnkr.co/edit/rDkXpIgiOSoNvLNPsVbP

我的目标:让Delete按钮工作并删除所选行

这是因为$index在父作用域上,但您在查询行指令中使用了隔离作用域。

尝试以下操作:

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

或者,删除隔离范围。