有没有办法以编程方式将 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/