AngularJS - Wait for the data to load to display the view

I'm really new to AngularJS, and after reading a few questions and some articles, I got a little confused about the correct way to load data and waited for it to load to display the view.

My controller is as follows

app.controller('ResultsController', ['$scope','$http', '$routeParams', function($scope, $http, $routeParams) {
    $scope.poll = {};
    $scope.$on('$routeChangeSuccess', function() {
        showLoader();
        $http.get("rest/visualizacion/" + $routeParams.id)
          .success(function(data) {
              $scope.poll = data;
              hideLoader();
           })
           .error(function(data) {
              // Handle error
           });
    });     
}]);

I saw that there are people who create a service for calling $ http, is this necessary? Why is it better?

+4
source share
1 answer

An appropriate way to do this is to use the resolveroute property . From the documentation :

resolve - {Object.<string, function>=} - , . - promises, , , . promises , promises $routeChangeSuccess. - promises , $routeChangeError. :

  • key - {string}: , .
  • factory - {string|function}: . , , , . , , . , ngRoute. $RouteParams . $route.current.params .

, , poneys , ,

resolve: {
    poneys: function($http) {
        return $http.get('/api/poneys').then(function(response) {
            return response.data;
        )};
    }
}

app.controller('PoneyListCtrl", function($scope, poneys) {
    $scope.poneys = poneys;
    // ...
});

, , $http, poneys .

+6

All Articles