javascript - 我可以从 ng-app 外部注册 ng-template

标签 javascript angularjs

有没有办法以编程方式将 ng-template 添加到 $templateCache。

HTML

<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.bootstrap,并将 ng-app 放在主体上,但我正在尝试设计这个模块,因此它可以嵌套在现有的 ng-app 中,或独立使用。当它在现有的 ng-app 中使用时,Angular 知道它,但当它单独使用时,Angular 不知道指令模板。

最佳答案

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

 angular.module('myApp', [])
   .controller('MyCtrl', MyCtrl)
   .directive('myDirective', myDirective)

 angular.module('myApp')
  .run(['$templateCache', function($templateCache) {
    $templateCache.put('myTemplate.html',
      'I\'m a template'
    );
  });

关于javascript - 我可以从 ng-app 外部注册 ng-template,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39002381/

相关文章:

javascript - webcl 和 webgl 不能同时工作

javascript - PhantomJS 和 Selenium Webdriver - 如何抓取由 js 加载的下一页表

javascript - 我正在使用ajax获取。 Controller 中的响应是正确的,但在ajax中返回404错误

javascript - Requirejs + Backbone 未捕获类型错误 : Cannot read property 'Model' of undefined

logging - 需要引用$log.log调用行号

javascript - 在 AngularJS 中使用 Jasmine 测试元素数量

angularjs - ui-bootstrap 日期选择器不工作

javascript - 在 Angularjs 中通过 IP 地址获取用户的位置

javascript - AngularFire 数据未显示在列表应用程序中

javascript - Google reCAPTCHA、405 错误和 CORS 问题