1

我正在尝试在 AngularStrap 弹出窗口中加载模板文件,但是我在使用 $templateCache 时遇到了问题。我似乎比其他 SO 问题更退一步,因此这似乎是双重问题。

在 API 文档之后,我在结束标记<script type="text/ng-template" id="popoverTemplate.html"></script>之前添加了一个。</body>当我<div ng-include="'popoverTemplate.html'"></div>在我的页面上使用时,我什么也得不到。如果我尝试使用console.log($templateCache.get("popoverTemplate.html"))我得到“$templateCache is not defined”,这导致我假设我错过了一个关键步骤。但是,我在文档或其他 SO 问题中找不到如何操作。

编辑:注入服务是缺少的链接。但是,当我注入服务时,控制器的其他功能不再起作用,但是如果您注入所有函数的参数,则工作代码将变为:

(function() {
    "use strict";
    angular.module("app").controller("managerController", ["$scope", "imageHierarchyRepository", "$templateCache", function ($scope, imageHierarchyRepository, $templateCache) {
        imageHierarchyRepository.query(function(data) {
            $scope.hierarchies = data;
        });

        var template = $templateCache.get("popoverTemplate.html");
        console.log(template);
    }]);
})();
4

2 回答 2

4

使用模板脚本标签。您必须将其插入到角度应用程序中。ng-app如果您不使用ng-app标签,那是在具有属性的元素内或用于引导应用程序的元素内。

<body ng-app="myapp">

  <div ng-template="'myTemplate.html'"></div>

  <script type="text/ng-template" id="myTemplate.html">
    // whate ever
  </script>
</body> 

如果要检索应用程序组件上的模板,则需要在要使用它的位置注入服务:

controller('FooCtrl', ['$templateCache', function ($templateCache) {
  var template = $templateCache.get('myTemplate.html');
}]);

或者

controller('FooCtlr', FooCtrl);

FooCtrl ($templateCache) {};

FooCtrl.$inject = ['$templateCache'];

编辑

不要注册两个具有相同名称的控制器,因为这样会用最后一个覆盖第一个。

(function() {
    "use strict";
    angular.module("app").controller("managerController",["$scope", "imageHierarchyRepository", "$templateCache", function ($scope, imageHierarchyRepository, $templateCache) {
        var template = $templateCache.get("popoverTemplate.html");
        console.log(template);
        imageHierarchyRepository.query(function(data) {
            $scope.hierarchies = data;
        });
    }]);


})();
于 2016-01-28T09:49:36.020 回答
0

小补充:虽然实现目标的方法很少,比如将整个 HTML 包装在<script>标签中等等,但对我来说最好的方法是将$templateCache逻辑添加到每个 Angular 指令中。这样,我可以避免使用任何外部包,例如grunt angular-templates(这对我的应用程序来说非常好但过度杀伤力)。

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

希望这可以帮助!

于 2016-05-01T13:01:53.797 回答