mha*_*sch 2 angularjs angularjs-directive
在我正在处理的应用程序中,服务为应用程序提供了一个包含HTML的json.我在这样的模板中输出HTML:
<div ng-bind-html="renderHtml(widget.article.body)"></div>
Run Code Online (Sandbox Code Playgroud)
此HTML可能包含自定义指令,如内联图表:
directiveModule.directive('inlineChart', function(){
return {
restrict: 'A',
scope: { inline-widget:'=elem' },
template: '<p ng-bind="inline-widget.blah"></p>'
};
});
Run Code Online (Sandbox Code Playgroud)
如果我在模板中正常使用该指令,一切正常,但在使用带有renderHtml函数的ng-bing-html时似乎没有被触及.
任何有关如何实现这一点的建议都非常感谢!
添加此指令angular-bind-html-compile
.directive('bindHtmlCompile', ['$compile', function ($compile) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
scope.$watch(function () {
return scope.$eval(attrs.bindHtmlCompile);
}, function (value) {
// Incase value is a TrustedValueHolderType, sometimes it
// needs to be explicitly called into a string in order to
// get the HTML string.
element.html(value && value.toString());
// If scope is provided use it, otherwise use parent scope
var compileScope = scope;
if (attrs.bindHtmlScope) {
compileScope = scope.$eval(attrs.bindHtmlScope);
}
$compile(element.contents())(compileScope);
});
}
};
}]);
Run Code Online (Sandbox Code Playgroud)
像这样使用它:
<div bind-html-compile="data.content"></div>
Run Code Online (Sandbox Code Playgroud)
真的很容易:)