eggman eggman - 5 months ago 12
AngularJS Question

Problems setting up data in UI-grid

I´m struggling with UI-grid trying to set it up properly.

I have a datastructure similar to this:

var arr = [
{'name': 'a', age: '1'},
{'name': 'b', age: '2'},
{'name': 'c', age: '3'},
{'name': 'd', age: '4'},
{'name': 'e', age: '5'}
];


Im trying to present the data using
name
as columnHeader and
age

as its data. So I would like the result to consist of only two rows.

Here is the code I am using:

$scope.gridOptions = {
enableSorting: true,
columnDefs: [],
data : []
};

var arr = [
{'name': 'a', age: '1'},
{'name': 'b', age: '2'},
{'name': 'c', age: '3'},
{'name': 'd', age: '4'},
{'name': 'e', age: '5'}
];

for (var i = 0; i < arr.length; i++) {
var name = arr[i].name.toString();

$scope.gridOptions.columnDefs.push({ name:name, field: 'age' });

}


}]);


plunker

SSH SSH
Answer

try this

      var d = [];   
      for (var i = 0; i < arr.length; i++) {
            var name = arr[i].name.toString();
            $scope.gridOptions.columnDefs.push({ name:name, field: 'age' });
            var a = $scope.gridOptions.columnDefs[i].name;
            var model = new Object();
            model[a]=arr[i].age; 
             d.push(model); 

          } 

       $scope.gridOptions = { data: d };