1

我有以下兩個指令。一個是查詢生成器,另一個是查詢行。查詢構建器指令使用ng repeat來列出數組中的查詢行。添加按鈕的作品,但我想包括一個刪除按鈕。然而,問題是,我似乎無法得到$指數,這樣我可以把它作爲參數傳遞給刪除功能(即刪除($指數))

下面是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> 

這裏是刪除按鈕(查詢行模板的一部分)。這裏的$指數「未定義」當我試圖把它作爲參數傳遞

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

這裏的plunker http://plnkr.co/edit/rDkXpIgiOSoNvLNPsVbP

我的目標:獲得一個刪除按鈕的工作,並刪除所選的行

+0

我不知道爲什麼這不起作用,但你不需要包含$ index索引。 ng-repeat會自動創建在重複 – efarley

回答

2

這是因爲$索引位於父範圍內,但您在query-row指令中使用隔離範圍。

嘗試以下方法:

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

可替代地,除去該分離範圍。

+0

內部可用的$索引。但是,這是否有更好的方法呢?我留下的印象是,如果在層次結構中添加更多父指令,可能會出現複雜情況,因此可以避免使用$ parent。或者我錯了 – user1142130

+0

你的查詢行指令('scope:{}')需要隔離範圍嗎?嘗試刪除,並刪除'$ parent.'。您可以將其更改爲'scope:false'或'scope:true'。請參閱https://docs.angularjs.org/api/ng/service/$compile#directive-definition-object下的範圍部分 –