AngularJS retrieve data via AJAX before Directive runs

后端 未结 3 1473
花落未央
花落未央 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:14

    You could just delay execution of ui-map until your data is loaded.

    HTML:

    <div ui-if="loadingIsDone">
      <div ui-map="myMap" ui-options="myOpts"></div>
    </div>
    

    JS:

    $http.get('/mapdata').then(function(response) {
      $scope.myOpts = response.data;
      $scope.loadingIsDone = true;
    });
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-04 06:35

    Generally, what you can do is have your directive get set up, start the load and finish in the success. I'm assuming you want to load one piece of data for all instances of your directive. So here's some psuedo-code for how you might want to attack this:

    app.directive('myDelayedDirective', ['$http', '$q', function($http, $q) {
    
      //store the data so you don't load it twice.
      var directiveData,
          //declare a variable for you promise.
          dataPromise;
    
      //set up a promise that will be used to load the data
      function loadData(){ 
    
         //if we already have a promise, just return that 
         //so it doesn't run twice.
         if(dataPromise) {
           return dataPromise;
         }
    
         var deferred = $q.defer();
         dataPromise = deferred.promise;
    
         if(directiveData) {
            //if we already have data, return that.
            deferred.resolve(directiveData);
         }else{    
            $http.get('/Load/Some/Data'))
              .success(function(data) {
                  directiveData = data;
                  deferred.resolve(directiveData);
              })
              .error(function() {
                  deferred.reject('Failed to load data');
              });
         }
         return dataPromise;
      }
    
      return {
         restrict: 'E',
         template: '<div>' + 
              '<span ng-hide="data">Loading...</span>' +
              '<div ng-show="data">{{data}}</div>' + 
            '</div>',
         link: function(scope, elem, attr) {
             //load the data, or check if it's loaded and apply it.
             loadData().then(function(data) {
                 //success! set your scope values and 
                 // do whatever dom/plugin stuff you need to do here.
                 // an $apply() may be necessary in some cases.
                 scope.data = data;
             }, function() {
                 //failure! update something to show failure.
                 // again, $apply() may be necessary.
                 scope.data = 'ERROR: failed to load data.';
             })
         }
      }
    }]);
    

    Anyhow, I hope that helps.

    0 讨论(0)
提交回复
热议问题