Using $http and $templateCache from within a directive doesn't return results

后端 未结 2 728
北荒
北荒 2021-02-04 15:04

I am trying to create a directive that would load a template. The template will then be cached so the second time you click on the element it would not try to load it but instea

2条回答
  •  南旧
    南旧 (楼主)
    2021-02-04 15:20

    I would suggest creating a separate service that will do the job:

    YourModule.factory('Utils', ['$q', '$http', '$templateCache', function ($q, $http, $templateCache) {
        var Service = function() {
    
        };
    
        Service.prototype.TemplatePromise = function (keyOrUrl) {
            var data = $templateCache.get(keyOrUrl);
    
            if (data) {
                return $.when(data);
            } else {
                var deferred = $.defer();
    
                $http.get(keyOrUrl, { cache: true }).success(function (html) {
                    $templateCache.put(keyOrUrl, html);
    
                    deferred.resolve(html);
                });
    
                return deferred.promise;
            }
        };
    
        return new Service();
    }]);
    

    Using this approach will add flexibility and isolation to the way you get templates, most probably you would want it to be done your own independent way...

提交回复
热议问题