简体   繁体   中英

AngularJS Prefetch data from directive

Is there any way in AngularJS to prefetch the data from url. I heard of template cache. Can template cache load the contents from path ? I have created a directive, But I am facing problems. When I am using template, preloading the html, but when I am using templateURL, it's not preloading the html from path, only loading when it's needed. But I need data to be preloaded. Is that possible ?

cmsApp.directive('ptnPopup', function() {
    return {
        restrict: 'E',
        transclude: true,
        controller: 'MainCtrl',
        template: '<div>{{bid}}</div>',
       //templateUrl: './template/popups/primary_trading_name.html',
       link: function(scope, element, attrs) {
             scope.bid = 5;
        }
    };
});

The easiest and most hands-off approach for this is to introduce a task into your project that generates templates cache based on your templates.

like https://github.com/ericclemmons/grunt-angular-templates

It will essentially generate a js file based on your templates that will preload all of them into $templatecache. Once this js is loaded, no further ajax requests will be made to your templates and you can keep using templateURL syntax in your directive definitions.

angular.module('app').run(["$templateCache", function($templateCache) {
  $templateCache.put("home.html",
    // contents for home.html ...
  );
  ...
  $templateCache.put("src/app/templates/button.html",
    // contents for button.html
  );
}]);

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