2

I want to make a dynamic ng-grid , which adjusts its columns according to the key values in my JSON object. JSON object is fetched from an api. the problem I am facing is defining columns at runtime i.e The columns are not available at design time but will only be available only at runtime. I want to have something like :

http://plnkr.co/edit/q1Ye10OsIn9NOJmrICyD?p=preview

So that, I have as many columns as keys in my Json object. API's can vary so I need to make a grid which adjusts its columns.

My plunker is not working, but I hope it gives you idea, what I am trying to do.

2 Answers 2

2

Unless I'm misunderstanding what you want, you don't need to mess with columnDefines. Just having this:

faculty.controller('facultycontroller', function facultycontroller($scope, $http, $window){
    $scope.facdata = [];
    
    $scope.gridOptions = {
      data: 'facdata'
    };

    $http.get("http://mtapi.azurewebsites.net/api/institute").then(function (result) {
         $scope.facdata = result.data;
         console.log($scope.facdata[0]);
    });
});

will create the grid with a column for each key in your json.

Update

If you want to filter out any columns that begin with '$', you can do something like this:

angular.forEach(result.data[0], function(value, key){
    if(key.indexOf('$') != 0)
        $scope.columnDefines.push({ field: key, displayName: key});
}); 

Actually, you were close with what you were trying to do. You just need to put the columnDefines variable on $scope, and assign it to the gridOptions using a string, like this:

$scope.columnDefines = [];

$scope.gridOptions = {
  data: 'facdata',
  columnDefs: 'columnDefines'
};

Plunker

Sign up to request clarification or add additional context in comments.

1 Comment

I have tried this. This has a problem, it prints some additional columns, for example, $id, i dont want it to get printed but it will if i go by this method. Thank you for your help though.
0

Try attaching your columnDefines variable to the scope ($scope.columnDefines). Then in your options do this:

$scope.gridOptions = 
  {
    data: 'facdata',
    columnDefs: 'columnDefines' //Note the quotes            
  };

This will make ng-grid watch your columnDefs for changes

1 Comment

columndefines is correctly defined, as grid is showing that column(student) I have defined inside it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.