aravindtrue aravindtrue - 1 month ago 27
Javascript Question

Angular UI Grid - Add or remove columns and update data

I am trying to add/remove columns from the grid and update the data. Here is the Plunker

HTML

<div ng-controller="MainCtrl">
<div id="grid1" ui-grid="settings" class="grid"></div>

<button ng-click="add();">Add</button>
</div>


JS

app.controller('MainCtrl', ['$scope', function($scope) {
$scope.result = [{
"firstName": "Cox",
"lastName": "Carney",
"company": "Enormo",
"employed": true
}, {
"firstName": "Lorraine",
"lastName": "Wise",
"company": "Comveyer",
"employed": false
}, {
"firstName": "Nancy",
"lastName": "Waters",
"company": "Fuelton",
"employed": false
}];

$scope.column_defs = [{
name: 'First Name',
field: 'firstName'
}, {
name: 'Last Name',
field: 'lastName'
}, {
name: 'Company',
field: 'company'
}];

$scope.settings = {
data: $scope.result,
columnDefs: $scope.column_defs
};

$scope.add = function() {
$scope.column_defs = [{
name: 'First Name',
field: 'firstName'
}, {
name: 'Last Name',
field: 'lastName'
}, {
name: 'Company',
field: 'company'
}, {
name: 'Employed',
field: 'employed'
}];

$scope.result = [{
"firstName": "Cox",
"lastName": "Carney",
"company": "Enormo",
"employed": true
}, {
"firstName": "Lorraine",
"lastName": "Wise",
"company": "Comveyer",
"employed": false
}];
};
}]);


When we click 'Add' button, nothing happens whereas I am expecting to update the
columnDefs
and
data
.

Thanks in advance.

Answer

UI grid binds to $scope.settings. You need to refresh the $scope.settings variable to refresh the grid. Add this in $scope.add:

$scope.settings = {
    data: $scope.result,
    columnDefs: $scope.column_defs
  };
Comments