一种解决方案是将ngInclude与$
templateCache一起使用,如本Plunker所示。
有几件事要注意。
第一个是,你可以使用服务获取您的模板,并将其添加到$templateCache,(例如复制):
myApp.service('myTemplateService', ['$http', '$templateCache', function ($http, $templateCache) { $http().then(function (result) { $templateCache.put('my-dynamic-template', result); });}]);然后可以将其包含在模板中,如下所示:
<div ng-include="'my-dynamic-template'"></div>
ngInclude将允许对html字符串进行数据绑定,因此您不需要ngBindHtml。
第二个原因是,当ngInclude创建新作用域时,
html除非您通过父作用域上的对象(例如
ng-model="data.html"而不是)访问新创建作用域之外的属性,否则将无法正常访问该属性(
ng-model="html"请注意,
$scope.data={}父作用域中的是是什么使得html在ngInclude范围之外可以访问。编辑
正如您所指出的那样,使用服务返回HTML时,ngInclude选项的用处不大。
这是经过编辑的plunker,具有使用$
compile的基于指令的解决方案,如上述David的评论所示。
相关补充:
app.directive('customHtml', function($compile, $http){ return { link: function(scope, element, attrs) { $http.get('template.html').then(function (result) { element.replaceWith($compile(result.data)(scope)); }); } }})


