5

我是 AngularJS 的初学者。我研究了 ng-grid 的演示并有一个问题。

索引.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>

应用程序.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;

});

当我选择第一行时, selectedItems 的 div 将显示 [{"name":"Moroni","id":1}]。结果没问题。如果我只想从选定的行中获取单元格 [id] 的值,我该如何修改我的代码?

这是 Plunker

4

3 回答 3

5

使用afterSelectionChange回调将 id 从选择中提取到另一个数组。

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

现在您可以{{selectedIDs}}从模板中引用并在其中包含所有选定的 id。或者只是第一个:{{selectedIDs[0]}}

请参阅此处的工作示例:http: //plnkr.co/edit/xVwVWX

于 2013-06-04T08:26:08.523 回答
2

您可以使用 afterSelectionChange 事件的参数访问所选行的 rowItem。实体属性将具有 id 和 name 属性。

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

};

于 2013-09-11T14:55:46.323 回答
0

Acutally, I want to get a cell value and modify when user selects the cell at the table.

Above answers are using fixed columns's filed.. like

 $scope.selectedIDs.push( item.id ) // id is column filed

Instead of these answers, I found another way exactly what I want to achieve with.

Example code: http://plnkr.co/edit/wfiMhlJ7by4eUHojjKT4?p=preview

editableCellTemplate which is an option for columnDefs is used for solving this problem.

Angular is Aswome!!

于 2015-06-17T08:38:00.000 回答