AngularJS中插入HTML片段
来源:互联网 发布:网络学历 编辑:程序博客网 时间:2024/06/06 20:52
我们知道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。
0 0
- AngularJS中插入HTML片段
- angularjs,ng-include引入html代码片段
- 防止jinja2自动转义,以将数据库中的html片段插入到所在html中(以html输出,而非HTML代码输出)
- jsp页面中插入jsp代码片段
- angularjs中防止HTML转义
- html中插入背景音乐
- HTML中插入flash
- html中插入mediaplayer
- html中插入图片
- html中插入map
- html中插入图片
- HTML文件中引入其他HTML代码片段
- 在PPT中播放插入flash的指定片段
- AngularJS中如何绑定html内容
- angularjs中ng-bind-html使用问题
- xsl中插入HTML特殊符号
- iframe中如何插入html
- iframe中如何插入html
- vb
- dobbo配置
- Configuring Locations(配置locations)
- 十进制换化为二进制
- [BZOJ1934][Shoi2007]Vote 善意的投票(最小割)
- AngularJS中插入HTML片段
- Java 8怎么了:局部套用vs闭包
- 负载均衡
- 关于响应链的问题自我简单理解
- 秒杀多线程第三篇 原子操作 Interlocked系列函数
- 磁阻 磁饱和
- linux大文件分包压缩和批量解压命令tar
- 23转化为二进制数
- 二进制