您的位置:首页 > Web前端 > AngularJS

AngularJS中插入HTML片段

2016-04-28 16:43 579 查看
我们知道angular中默认是不信任不支持HTML内容的,所以对于要添加的

HTML 要先使用 $sce.trustAsHtml(html_in_string) 将标记为信任,然后使用 data-ng-bind-html="html_in_string" 取消转义才能使用。

js

.controller('ModalWithSelectCtrl', function($scope,$sce) {
$scope.modalBody=$sce.trustAsHtml("<h1>2222</h1>")
})


html

<div  data-ng-bind-html="modalBody"></div>


对于纯html来说,这个插入就完成了。

但对于复杂的html,比如是带有angular表达式,指令的html,

因为ng-bind-html并不会和$scope产生关系的,

如果在htm中存在ng-show,ng-href...这些angular指令,它们就不会被compile也就不会有任何反应了,绑定的表达式不会被更新而直接显示出来。

我们知道,在angular中所有指令要生效,都需要经过compile,在compile中包含了pre-link和post-link,链接上特定的行为,才能工作。

大部分complie都会在angular启动时候,自动compile的,

但如果是对于动态添加的模板,则需要我们手动compile了。

angular已经为我们提供了$compile服务来实现。

下面我们修改上述例子

htm

<dy-compile    html="{{modalBody}}"></dy-compile>


js

$scope.modalBody=$sce.trustAsHtml('<p  ng-show="is_no_user">please select user</p> <p ng-show="is_has_user"><b class="font_color" >{{selectNum}}</b> users have been selected<br>these users Click on OK to<b class="font_color ml5" >{{selectAction}}</b></p>')


下面这个就是我们用来手动compile的directive

.directive("dyCompile", ["$compile", function($compile) {
return {
replace: true,
restrict: 'EA',
link: function(scope, elm, iAttrs) {
var DUMMY_SCOPE = {
$destroy: angular.noop
},
root = elm,
childScope,
destroyChildScope = function() {
(childScope || DUMMY_SCOPE).$destroy();
};

iAttrs.$observe("html", function(html) {
if (html) {
destroyChildScope();
childScope = scope.$new(false);
var content = $compile(html)(childScope);
root.replaceWith(content);
root = content;
}

scope.$on("$destroy", destroyChildScope);
});
}
};
}])


这里创建了一个叫dy-compile的指令,它首先会监听绑定属性html值的变化,当html内容存在的时候,它会尝试首先创个一个子scope,然后利用$compile服务来动态连接传入的html,并替换掉当前DOM节点;这里创建子scope的原因,是方便在每次销毁DOM的时,也能容易的销毁掉scope,去掉HTML compile带来的watchers函数,并在最后的父scope销毁的时候,也会尝试销毁该scope。

因为有了上边的compile的编译和连接,则ng-show指令就可以生效了。这里只是尝试给出动态compile angular模块的例子,具体的实现方式,请参照你的业务来声明特定的directive。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: