Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the cell value from ng-grid

I am a beginner of AngularJS. I study the demo of ng-grid and have a question.

index.html

<!DOCTYPE html>
<html ng-app="myApp">

<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<link rel="stylesheet" type="text/css" href="http://angular-ui.github.com/ng-grid/css/ng-grid.css" />
<link rel="stylesheet" type="text/css" href="style.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.min.js"></script>
<script type="text/javascript" src="http://angular-ui.github.com/ng-grid/lib/ng-grid.debug.js"></script>
<script src="app.js"></script>
</head>

<body ng-controller="MyCtrl">
    <div class="gridStyle" ng-grid="gridOptions"></div>
    <div class="selectedItems">{{mySelections}}</div><br><br>

</body>

</html>

app.js

var app = angular.module('myApp', ['ngGrid']);
app.controller('MyCtrl', function($scope) {
$scope.mySelections = [];
$scope.myData = [{name: "Moroni", id: 1},
                 {name: "Tiancum", id: 2},
                 {name: "Jacob", id: 3},
                 {name: "Nephi", id: 4},
                 {name: "Akon", id: 5},
                 {name: "Enos", id: 6}];
$scope.gridOptions = { 
data: 'myData',
selectedItems: $scope.mySelections,
multiSelect: true 
};

//$scope.mySelections_id = $scope.mySelections.length;

});

When I select the first row, the div of selectedItems will show [{"name":"Moroni","id":1}]. the result is OK. If I just want to get the value of cell [id] from selected row, how do I modify my code?

here is Plunker

like image 934
Tom Cheng Avatar asked Jun 04 '13 06:06

Tom Cheng


2 Answers

Use the afterSelectionChange callback to extract the ids from the selection to an other array.

$scope.gridOptions = { 
    data: 'myData',
    selectedItems: $scope.mySelections,
    multiSelect: true,
    afterSelectionChange: function () {
      $scope.selectedIDs = [];
      angular.forEach($scope.mySelections, function ( item ) {
        $scope.selectedIDs.push( item.id )
      });
    }
  };

now you can reference {{selectedIDs}} from the template and has all the selected ids in it. Or just the first: {{selectedIDs[0]}}

See the working example here: http://plnkr.co/edit/xVwVWX

like image 113
Oliver Avatar answered Nov 15 '22 22:11

Oliver


You can access the rowItem of the selected row with the arguments to the afterSelectionChange event. The entity property will have the id and name properties.

 $scope.gridOptions = { 
    data: 'myData',
    selectedItems: $scope.mySelections,
    multiSelect: true,
    afterSelectionChange: function (theRow, evt) {      
       alert(theRow.entity.id);
}

};

like image 45
Crowcoder Avatar answered Nov 15 '22 20:11

Crowcoder