angularjs - 从文件加载 $templateCache

标签 angularjs templates

我一直在从 $templateCache 加载模板时遇到问题。

我如何将模板放入 $templateCache :

var app = angular.module('anglober', ['anglober.controllers', 'anglober.services', 'anglober.directives']).run(function ($templateCache, $http) {
    $http.get('anglober/js/invitation/invitationModal.tpl.html', {cache: $templateCache});
    $http.get('anglober/js/modal/ajaxModal.tpl.html', {cache: $templateCache});
    $http.get('anglober/js/ajaxLoader/ajaxLoader.tpl.html', {cache: $templateCache});
    $http.get('anglober/js/modal/modalContent.tpl.html', {cache: $templateCache});
    $http.get('anglober/js/modal/simpleModal.tpl.html', {cache: $templateCache});
    $http.get('anglober/js/mog/topMogs.tpl.html', {cache: $templateCache});

我如何加载它们:
angular.module('anglober.directives').directive('topMogs', ['$templateCache', function ($templateCache) {
return {
    restrict : 'E',
    template: $templateCache.get('topMogs.tpl.html')
    //Tried this too
    // templateUrl: 'topMogs.tpl.html'
};
}]);

在我的网络浏览器选项卡中,我可以看到页面加载时正在加载的模板。

但是,在调用指令时出现以下错误:
One of template or templateUrl options is required.

我究竟做错了什么 ?

谢谢

最佳答案

这个旧线程的一个小补充:
虽然有几种方法可以实现您的目标,但对我来说最好的方法是添加 $templateCache逻辑到我的每个应用程序的指令中。这样,我可以避免使用任何外部包,如 grunt angular-templates (这很好 - 但对我的应用程序来说有点矫枉过正)

angular.module('MyApp')
.directive('MyDirective', ['$templateCache', function($templateCache) {
    return {
        restrict: 'E',
        template: $templateCache.get('MyTemplate'),
        controller: 'MyController',
        controllerAs: 'MyController'
    };
}]).run(function($templateCache, $http) {
    $http.get('templates/MyTemplate.html').then(function(response) {
        $templateCache.put('MyTemplate', response.data);
    })
});
希望这可以帮助!

关于angularjs - 从文件加载 $templateCache,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27649301/

相关文章:

angularjs - 如何使用 Smart-Table 提高 ng-repeat 性能?

C++ 虚拟模板方法

c++ - 覆盖不明确的继承

php - 使用模板发送电子邮件 (Mandrill PHP)

c++ - 如何使此函数使用 getline 读取字符串并使其与 int 的行为相同?

c++ - 从基类指针集合中调用非虚拟成员函数?

javascript - 指令中的 AngularJS 模板函数给出错误 'Template for directive must have exactly one root element'

javascript - ng-repeat 将某些值保存为 cookie

javascript - 在 Bootstrap 可折叠侧边栏导航中添加 Cookie

javascript - Angular JS 中的嵌套 ng-repeat