AngularJS retrieve data via AJAX before Directive runs

后端 未结 3 1468
花落未央
花落未央 2021-02-04 05:32

I\'m using AngularUI\'s uiMap directives to instantiate a google map. The uiMap directive works great with hard-coded data ({mapOptions} and

3条回答
  •  清歌不尽
    2021-02-04 06:18

    I am not sure if this will help without seeing code, but I ran into this same issue when I was creating my $scope.markers object inside the $http.success function. I ended up creating the $scope.markers = [] before the $http function, and inside the .success function, I populated the $scope.markers array with the return data.

    So the $scope object was bound while the directive was compiling, and updated when the data returned.

    [UPDATE SUGGESTION]

    Have you tried taking advantage resolve in your route?

      function($routeProvider) {
        $routeProvider.
          when(
            '/',{
              templateUrl: 'main.html',
              controller: Main,
              resolve: {
                   data: function(httpService){
                       return httpService.get()
                   }
              }
          }).
          otherwise({redirectTo: '/'});
      }
    

    I usually put my $http requests in a service, but you could call the $http right from your route:

    App.factory('httpService'), function($http){
         return {
           get: function(){
               $http.get(url)
           }
        }
    });
    

    Then, in your controller, inject data and set your $scope items to the data.

提交回复
热议问题