AngularJS retrieve data via AJAX before Directive runs

后端 未结 3 1475
花落未央
花落未央 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: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: '
    ' + 'Loading...' + '
    {{data}}
    ' + '
    ', 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.

提交回复
热议问题