Get Ajax data into Angular grid

依然范特西╮ 提交于 2019-12-02 22:28:15

Your controller is probably accessing the getData array before the .success is finished. You're accessing the variable right away, outside of a promise function, which is initialized to an empty array.

Why don't you try putting the fetchData function into the controller (for now) and storing the getData directly into $scope.myData in the .success? Maybe even initialize the grid right there too? Not sure if you can do that but if you could it would look like this:

app.controller('MyCtrl', function($scope, $http) {  
$scope.myData = '';
$scope.gridOptions = { showGroupPanel: true, data: 'myData' };
function fetchData() {
    setTimeout(function(){  
        $http({
            url:'/url/to/hell',
            type:'GET'})
            .success(function(data) {
                $scope.myData = data;   
                if (!$scope.$$phase) {
                    $scope.$apply();
                }                   
            });         
    }, 3000);       
}   
fetchData();    
});

(source for some of the $scope apply stuff: https://github.com/angular-ui/ng-grid/issues/39)

Also not sure why you're mixing in jQuery .ajax with angular code ($http will do that), and why none of your javascript has a semicolon.

Benmj

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!