2016-05-31 59 views
1

我希望能夠在該行右鍵單擊時選擇該行。右鍵點擊UI網格選擇

到目前爲止,我有以下解決方案(我已經從here的想法):

我創建了一個右鍵指令是這樣的:

app.directive('rightClick', function($parse) { 
    return function(scope, element, attrs) { 
     var fn = $parse(attrs.rightClick); 
     element.bind('contextmenu', function(event) { 
     scope.$apply(function() { 
      event.preventDefault(); 
       fn(scope, {$event:event}); 
      }); 
     }); 
    }; 
}); 

,然後我可以在我的控制器中添加功能將被調用:

$scope.rightClick = function (event) { 
    var scope = angular.element(event.toElement).scope(); 
    if (scope.row.entity !== undefined) { 
     //... select element by calling gridApi 
    } 
}; 

添加指令與屬性right-click="rightClick($event)"是必修課。

該解決方案的問題在於它依賴於element.scope()這是一個角度調試功能,如果調試信息在生產中被禁用,將不可用。

所以,現在我正在尋找一種替代解決方案,無需element.scope()。所以問題是:「如何在不依賴於角度調試功能的情況下選擇右鍵點擊元素」。

回答

2

行ID存儲在其上可用於識別單擊的單元格的電池元件ID:

$scope.rightClick = function (event) { 
    var element = angular.element(event.toElement); 

    //get cellId which for the thrid row should something like this 
    //1464688691229-2-uiGrid-0006-cell 
    var id = element[0].parentElement.id; 

    var regex = /(\d+)/g 
    var result = id.match(regex); 
    var rowIndex = parseInt(result[1]); //extract second numeric match 

    $scope.gridApi.selection.selectRowByVisibleIndex(rowIndex);  
}; 

我說你可能需要實驗,看看如果該ID是可見索引或源數據的索引。我不確定,但我已經在這裏舉了一個實例。

http://plnkr.co/edit/b2RKW0hdtFk1ZOLn1XsS?p=preview

+0

有趣的解決方案。不幸的是,我在單元格div上沒有id。可能是因爲我使用自定義行模板。 – Sjoerd222888

+0

也許你可以在單元DOM元素上添加一個自定義屬性?還請注意,該id在父元素上,而不是單元格內容。 –

+0

我必須更改我的行模板,使其具有原始行模板的一些屬性(請參閱ui-grid源代碼中的'ui-grid/ui-grid-row'模板)。謝謝。 – Sjoerd222888

0

還可以定義行模板與NG-鼠標懸停參照一些範圍的方法(見下文$ scope.selectRowOnMouseOver),其將設置行(下鼠標光標)在一定範圍可變。然後你就可以使用這個變量來設置選擇你右擊方法:

定義行模板:

 //define row template with ng-mouseover reference to scope method 
    $scope.resultsGrid.rowTemplate = 
     "<div ng-dblclick=\"grid.appScope.doubleClickOnRow(row, $event)\" ng-repeat=\"(colRenderIndex, col) in" + 
     " colContainer.renderedColumns track by col.colDef.name\" class=\"ui-grid-cell\" ng-class=\"{ 'ui-grid-row-header-cell':" + 
     " col.isRowHeader }\" ng-mouseover=\"grid.appScope.selectRowOnMouseOver(row)\" ui-grid-cell></div>"; 

定義方法,將設置在光標範圍變量行(或一組選擇在該行的時候了) :在你右擊方法

$scope.selectRowOnMouseOver = function (row) { 
     $scope.rowUnderMouse = row; 
     //you can also select row right here or in other methods using above variable 
     $scope.gridApi.selection.clearSelectedRows(); 
     row.setSelected(true); 
    }; 

使用範圍變量:

$scope.rightClick = function (event) { 
     var row = $scope.rowUnderMouse; 
     //clear other selections 
     $scope.gridApi.selection.clearSelectedRows(); 
     //set row as selected 
     row.setSelected(true); 
     //... 
    }