Get the selected row object with ng-grid Angular-UI

Asked

Viewed 1,298 times

0

I’m using ng-grid of Angular-UI and need to get the selected object when clicked on the grid line.

I have the function:

$scope.selectItem = function(item)
{
    $scope.selectedItem = item;
}

I tried to write about the property rowTemplate of the object gridOptions to add the click directive, this way:

rowTemplate:'<div ng-style="{ "cursor": row.cursor }" ng-repeat.....;

The code above is the default value, so I added the first div the ng-click to invoke the Function:

rowTemplate:'<div ng-click="selectItem(o que passar aqui?)"ng-style.....;

How do I access the object present in the line clicked to pass in selectItem?

1 answer

1

I checked the ng-grid documentation. As in the "Master/Details" example, you can do so:

var app = angular.module('myApp', ['ngGrid']);
app.controller('MyCtrl', function($scope) {
    $scope.mySelections = [];
    $scope.myData = [{name: "Moroni", age: 50},
                     {name: "Tiancum", age: 43},
                     {name: "Jacob", age: 27},
                     {name: "Nephi", age: 29},
                     {name: "Enos", age: 34}];
    $scope.gridOptions = { 
      data: 'myData',
      selectedItems: $scope.mySelections,
      multiSelect: false
    };
});

The important thing here is the option selectedItems in gridOptions. You initialize a array empty and use option, which the array will be updated with the selected items.

In the API documentation, the option selectedItems is explained like this:

all selected items on the grid. In single selection mode (single select mode) there will always be only one item on array.


To make it clearer (step-by-step):

In your rowTemplate, do so:

rowTemplate:'<div ng-click="selectItem(mySelections[0])" ng-style.....;

In your controller, include:

$scope.mySelections = [];

And you will need to specify the option selectedItems in gridOptions:

$scope.gridOptions = { selectedItems: $scope.mySelections };

I mean, putting it all together:

$scope.selectItem = function(item)
{
    $scope.selectedItem = item;
}

$scope.mySelections = [];

$scope.gridOptions =
{
    selectedItems: $scope.mySelections,
    rowTemplate:'<div ng-click="selectItem(mySelections[0])" ng-style...'
};

In fact, it can be simpler. Anywhere in the controller you have access to the selected item with:

$scope.mySelections[0];

Or in HTML (assuming there is a "name property"):

<p>{{ mySelections[0].name }}</p>
  • Well, actually that’s not it. I need to add a click event to the selected row by passing the object of it, so I’ve overwritten the rowTemplate. But I’ll try and do that and report you, obrg.

  • If you do as in the example, just do ng-click="selectItem(mySelections[0])" in your rowTemplate

  • I updated the response with step-by-step instructions.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.