2017-06-08 73 views
0

我想從多個源獲取json,並希望在單個Angular UI網格中顯示它。在所有這些來源第一領域是常見的。結合多個json並在Angular UI Grid中顯示

數據格式:

來源:1

var one=[ 
     { col1: "Heading 1", col2: "First 12", col3: "First 13"}, 
     { col1: "Heading 2", col2: "First 22", col3: "First 23"}, 
     { col1: "Heading 3", col2: "First 32", col3: "First 33"}, 
     { col1: "Heading 4", col2: "First 42", col3: "First 43"}, 
     { col1: "Heading 5", col2: "First 52", col3: "First 53"} 
    ]; 

來源:2

var two=[ 
     { col1: "Heading 1", col2: "Second 12", col3: "Second 13"}, 
     { col1: "Heading 2", col2: "Second 22", col3: "Second 23"}, 
     { col1: "Heading 3", col2: "Second 32", col3: "Second 33"}, 
     { col1: "Heading 4", col2: "Second 42", col3: "Second 43"}, 
     { col1: "Heading 5", col2: "Second 52", col3: "Second 53"} 
    ]; 

我希望它被顯示在網格這樣

enter image description here

來源:

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

app.controller('MainCtrl', ['$scope', 'uiGridConstants', function($scope, uiGridConstants) { 

var one=[ 
     { col1: "Heading 1", col2: "First 12", col3: "First 13"}, 
     { col1: "Heading 2", col2: "First 22", col3: "First 23"}, 
     { col1: "Heading 3", col2: "First 32", col3: "First 33"}, 
     { col1: "Heading 4", col2: "First 42", col3: "First 43"}, 
     { col1: "Heading 5", col2: "First 52", col3: "First 53"} 
    ]; 1 
    1 
var two=[ 
     { col1: "Heading 1", col2: "Second 12", col3: "Second 13"}, 
     { col1: "Heading 2", col2: "Second 22", col3: "Second 23"}, 
     { col1: "Heading 3", col2: "Second 32", col3: "Second 33"}, 
     { col1: "Heading 4", col2: "Second 42", col3: "Second 43"}, 
     { col1: "Heading 5", col2: "Second 52", col3: "Second 53"} 
    ]; 

    var finalObj = { 

    "firstData":one, 
    "secondData":two 
    } 


    console.log("finalObj"+JSON.stringify(finalObj)); 


    $scope.gridOptions = { 
    columnDefs: [ 
     {field: 'firstData.col1', displayName: 'Column 1', width: 175}, 
     {field: 'firstData.col2', displayName: 'Column 2', width: '*'}, 
     {field: 'firstData.col3', displayName: 'Column 3', width: 120}, 
     {field: 'secondData.col2', displayName: 'Column 4', width: '*'}, 
     {field: 'secondData.col3', displayName: 'Column 5', width: 120} 
    ], 
    enableRowSelection: true, 
    onRegisterApi: function(gridApi) { 
     $scope.gridApi = gridApi; 
    } 
    }; 
    $scope.gridOptions=finalObj; 

}]); 

代碼:看到attaced Plunkr http://plnkr.co/edit/ZUyJQInnygirvfohIhQo

回答

1

1)$scope.gridOptions=finalObj;需要改變到$scope.gridOptions.data=finalObj;

2)$scope.gridOptions.data需要一個array

試試這個:

function merge(obj1, obj2){ 
    return obj1.map(function(o1){ 
     return Object.assign({}, o1, { 
     col4: obj2.find(function(o2){ return o1.col1 == o2.col1 }).col2, 
     col5: obj2.find(function(o2){ return o1.col1 == o2.col1 }).col3 
     }) 
    }) 
} 

var finalObj = merge(one, two); 

$scope.gridOptions.data=finalObj; 

Plunker