我可以从ng-app外部注册一个ng-template吗?

Can I register a ng-template from outside of ng-app

本文关键字:一个 ng-template ng-app 外部 注册 我可以      更新时间:2023-09-26

是否可以通过编程方式将ng-template添加到$templateCache中?

<script type="text/ng-template" id="myTemplate.html">
    I'm a template
</script>
<div id="appContainer" ng-controller="MyCtrl">
    <my-directive></my-directive>   
</div>

JS

var MyCtrl = blah;
var myDirective = function() {
    return {
        restrict: 'E',
        scope: {},
        templateUrl: 'myTemplate.html'
    }
};
/* Register templates here??? */
angular.module('myApp', [])
    .controller('MyCtrl', MyCtrl)
    .directive('myDirective', myDirective)
;
angular.bootstrap(document.getElementById('appContainer'), ['myApp']);

由于模板不在ng-app下,angular并不知道它的存在。最明显的是不要用angular。引导,并把ng-app上的身体,但我试图设计这个模块,所以它可以嵌套在一个现有的ng-app,或单独使用。当它在已有的ng-app中使用时,angular会知道它,但当它单独使用时,angular不会知道指令模板的存在。

创建模块后,可以在run函数中注册如下模板:

 angular.module('myApp', [])
   .controller('MyCtrl', MyCtrl)
   .directive('myDirective', myDirective)
 angular.module('myApp')
  .run(['$templateCache', function($templateCache) {
    $templateCache.put('myTemplate.html',
      'I''m a template'
    );
  });