Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a column at runtime in a grid using ui-grid

Hello all fellow programmers, my requirement is to add a column in a grid at runtime or dynamically using ui-grid. I am able to achieve the same using a button, but what I want is to override the predefined functionality of the icon which in on the header of grid used for sorting and some predefined tasks(), I want add one more functionality there

var app = angular.module('app', ['ngAnimate', 'ui.grid']);

app.controller('MainCtrl', ['$scope', '$http', 'uiGridConstants', function ($scope, $http, uiGridConstants) {
  $scope.columns = [{ field: 'name' }, { field: 'gender' }];
  $scope.gridOptions = {
    enableSorting: true,
    columnDefs: $scope.columns,
    onRegisterApi: function(gridApi) {
      $scope.gridApi = gridApi;
    }
  };
  
 
  
  $scope.add = function() {
    $scope.columns.push({ field: 'company', enableSorting: false });
  }

 

  $http.get('https://cdn.rawgit.com/angular-ui/ui-grid.info/gh-pages/data/100.json')
    .success(function(data) {
      $scope.gridOptions.data = data;
    });
}]);
.grid {
  width: 500px;
  height: 250px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!doctype html>
<html ng-app="app">
  <head>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular-touch.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular-animate.js"></script>
    <script src="http://ui-grid.info/docs/grunt-scripts/csv.js"></script>
    <script src="http://ui-grid.info/docs/grunt-scripts/pdfmake.js"></script>
    <script src="http://ui-grid.info/docs/grunt-scripts/vfs_fonts.js"></script>
    <script src="http://ui-grid.info/release/ui-grid-unstable.js"></script>
    <link rel="stylesheet" href="http://ui-grid.info/release/ui-grid-unstable.css" type="text/css">
    <link rel="stylesheet" href="main.css" type="text/css">
  </head>
  <body>

<div ng-controller="MainCtrl">
  Try clicking the Add button to add the company column.
  <br>
  <br>
  <button id="button_add" class="btn" ng-click="add()">Add</button>
  <div id="grid1" ui-grid="gridOptions" class="grid"></div>
</div>


    <script src="app.js"></script>
  </body>
</html>

of adding a column there

like image 613
irfan shafi Avatar asked Oct 20 '22 22:10

irfan shafi


1 Answers

You can use $watch in the add method:

$scope.add = function() {

    $scope.columns.push({ field: 'company', enableSorting: false });

    $scope.$watch('columns', function(newVal, oldVal){
         console.log('added');
    }, true);

}

and i noticed that you have a minified script before the doctype of document which should not have to be there.

like image 176
Jai Avatar answered Oct 27 '22 11:10

Jai