问题
So the issue I'm facing is I would like to update the field
property of a columnDef
definition to show a different value based on some configuration that's being passed into the directive. I have a dumbed down version in this plunk:
http://plnkr.co/edit/gmjUcQsnIOpqWwkoYiI8?p=preview
Clicking the button in that plunk should switch the emails from actual
to pretend
. It's looping over the columnDefs
on scope and then altering the field to be email.pretend
from email.actual
. Do I need some kind of "refresh" function after changing the columnDefs? I tried gridApi.core.refresh()
but that did not do anything. Thanks for any input!
回答1:
http://plnkr.co/edit/ujIpJFFGRAwNUKiy0Bnm?p=preview
$scope.otherColumn = {displayName: 'Pretend', field: 'email.pretend'};
//change the field - is this possible???
$scope.changeField = function changeField() {
$scope.otherColumn = $scope.columnDefs.splice(1, 1, $scope.otherColumn)[0];
}
You just add / remove the item from the columnDefs
array and it will do it.
回答2:
So I thought I could update my grid similar to this but by reassigning an array to the columnsDef like this
var a = true;
//change the field - is this possible???
$scope.changeField = function changeField() {
if (a) {
$scope.columnDefs = [{ field: 'name' }, {
displayName: 'Pretend',
field: 'email.pretend'
}];
} else {
$scope.columnDefs = [{ field: 'name' }, {
displayName: 'Email',
field: 'email.actual'
}];
}
a = !a;
};
If you put that in the plnkr you'll see it doesn't have any effect.
That's because the assignment doesn't change the $scope.gridApi. As @dave's answer suggests you need to modify the original columnsDef object from the initialization or the columns under the api won't be affected. I'm glad the code doesn't clone the object for the api or I'd have to dig into the api to make this change.
来源:https://stackoverflow.com/questions/33576691/how-to-update-the-columndef-of-an-angular-ui-grid-column-dynamically