我是ng-grid的新手。我们如何动态更新网格中的列和结果。
我创建了http://plnkr.co/edit/CwUVIzSKVNCMTgpOW87f?p=preview
脚本
var app = angular.module('myApp', ['ngGrid']); app.controller('MyCtrl', function($scope) {
$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',
columnDefs: [{field: 'name', displayName: 'Name'}, {field:'age', displayName:'Age'}]
};
$scope.update_columns = function($event){ console.log("asd")
$scope.myData = [{new_name: "Moroni", new_age: 50, pin: 123},
{new_name: "Tiancum", new_age: 43, pin: 345},
{new_name: "Jacob", new_age: 27, pin: 567},
{new_name: "Nephi", new_age: 29, pin: 789},
{new_name: "Enos", new_age: 34, pin: 012}
];
$scope.gridOptions.columnDefs = [
{field: 'new_name', displayName: 'New Name'},
{field:'new_age', displayName:'New Age'},
{field:'pin', displayName:'Pin'}
];
} });
在页面加载时,网格将显示一组结果,单击更改列时,我们需要更新结果和列。我现在实施的方式没有按预期工作。我做错了吗?
提前致谢。
答案 0 :(得分:17)
您必须在范围上设置列定义变体。您还可以使用表示范围属性的字符串定义配置属性columnDefs
。与data
的配置类似,这允许您观察范围字段并将其切换出来。
对js的更改:
var app = angular.module('myApp', ['ngGrid']);
app.controller('MyCtrl', function($scope) {
$scope.columns1 = [{field: 'name', displayName: 'Name'}, {field:'age', displayName:'Age'}];
$scope.columns2 = [{field: 'new_name', displayName: 'New Name'}, {field:'new_age', displayName:'New Age'},{field:'pin', displayName:'Pin'}];
$scope.columnsSelected = $scope.columns1;
$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',
columnDefs: 'columnsSelected'
};
$scope.update_columns = function($event) {
$scope.columnsSelected = $scope.columns2;
$scope.myData = [{new_name: "Moroni", new_age: 50, pin: 123},
{new_name: "Tiancum", new_age: 43, pin: 345},
{new_name: "Jacob", new_age: 27, pin: 567},
{new_name: "Nephi", new_age: 29, pin: 789},
{new_name: "Enos", new_age: 34, pin: 012}
];
}
});
答案 1 :(得分:1)
您实际上可以使用相同的数据集,因为Angular忽略了未在columnDefs / columnsSelected中定义的列:
app.controller('MyCtrl', function($scope) {
$scope.columns = [];
$scope.columns[true] = [{field: 'name', displayName: 'Name'}, {field:'age', displayName:'Age'}];
$scope.columns[false] = [{field: 'name', displayName: 'New Name'}, {field:'age', displayName:'New Age'},{field:'pin', displayName:'Pin'}];
$scope.displayFlag = true;
$scope.columnsSelected = $scope.columns[$scope.displayFlag];
$scope.myData = [
{name: "Moroni", age: 50, pin: 123},
{name: "Tiancum", age: 43, pin: 345},
{name: "Jacob", age: 27, pin: 567},
{name: "Nephi", age: 29, pin: 789},
{name: "Enos", age: 34, pin: 012}
];
$scope.gridOptions = {
data: 'myData',
columnDefs: 'columnsSelected'
};
$scope.update_columns = function($event) {
$scope.displayFlag = !$scope.displayFlag;
$scope.columnsSelected = $scope.columns[$scope.displayFlag];
}
});