Get Ajax data into Angular grid

后端 未结 2 1261
梦如初夏
梦如初夏 2021-02-05 07:19

Using Angular Grid, I get the ajax get data in console.log. But an empty grid.

The console log reads:

[13:56:11.411] now!!
[13:56:11.412] []
[13:56:11.4         


        
2条回答
  •  灰色年华
    2021-02-05 07:32

    This would be much easier (and more Angular) if you defined a service for your request. Something along these lines:

    angular.module('hellServices', ['ngResource'])
      .factory('Hell', function ($resource) {
        return $resource('URL/TO/HELL', {}, {
          query: { method: 'GET' }
        });
      });
    

    Make sure to include it in your app:

    var app = angular.module('myApp', ['ngGrid', 'hellServices']);
    

    Then you can get a promise for it in your controller:

    app.controller('MyCtrl', function($scope, $http, Hell) {  
    $scope.myData = Hell.query();
    

    And then set the grid options to look at the promise for its data (as you already did):

    $scope.gridOptions = { 
        data: 'myData',
        showGroupPanel: true
    };
    

    If you do this, you don't have to worry about $scope.$apply because it will be handled for you. This is much cleaner and easier to follow. If you still need a callback to modify the data once it's returned from the server, pass a function to the query() function of your service:

    ...
    $scope.myData = Hell.query(function(hell) {
        // code that modifies 'hell'
    });
    

    Check out the official docs on Angular Services. The basics are also covered in Step #11 of the official Angular JS tutorial.

提交回复
热议问题