简体   繁体   中英

Where to store remote data used by directive inside ngView? (AngularJS)

Just for example:

I have directive inside ngView with this structure:

.directive('features', function() {
    templateUrl: '.../',
    link: function(scope) {
        // HTTP req, getting remote data.
        // Store the remote data to the scope
    }
})

When I change the route and return it back, the directive link option is executed again, the scope is empty. It need to wait some time for data-response from the remote server and then showing the data. I trying to avoid the layout stretching.

I am new to angular, I was read the documentation.

My question is: In this case, where the data is good to be saved? Do I need to make a controller? Or I can just cache it?

Note: This directive repeating an array (remote data) and making "features" HTML layout. This directive will be used in another routes with another behaviors.

I do not need code explanations, I can read docs. I accept terminology.

You could store the data in a service, basically to act as a cache as you mentioned. If you need to have that data available on page reloads (hard refresh, your app is reloaded again) you can store it in a cookie/local storage.

app.service("featuresService",function($http){
 var cachedFeatures=null;
 return{
   getFeatures:function(callback){
     if(!cachedFeatures){
       $http.get("...").success(function(data){
             cachedFeatures=data;
             callback(data);
       })
     }else{
             callback(cachedFeatures);
     }

   }
 }
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM