AngularJS 不得不了解的服务 $compile 用于动态显示html内容

项目中一度纠结与AngularJS如何动态显示不同的html内容。

本来是希望直接使用下面的语句来实现:

      
      
1
      
      
<div> </div>

但是很尴尬的是,这样不能识别出html标签,而是直接将html里的页面标签全都显示出来了。这当然不是我想要的效果。

谷哥了一番,没想到在官网上就找到了我想要实现的效果,而实现的主角就是今天的 $compile 服务。

https://docs.angularjs.org/api/ng/service/$compile

节选一下关键部分内容,Javascript:

      
      
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
      
      
<script>
angular.module( 'compileExample', [], function($compileProvider) {
// configure new 'compile' directive by passing a directive
// factory function. The factory function injects the '$compile'
$compileProvider.directive( 'compile', function($compile) {
// directive factory creates a link function
return function(scope, element, attrs) {
scope.$watch(
function(scope) {
// watch the 'compile' expression for changes
return scope.$ eval(attrs.compile);
},
function(value) {
// when the 'compile' expression changes
// assign it into the current DOM
element.html(value);
// compile the new DOM and link it to the current
// scope.
// NOTE: we only compile .childNodes so that
// we don't get into infinite loop compiling ourselves
$compile(element.contents())(scope);
}
);
};
});
})
.controller( 'GreeterController', [ '$scope', function($scope) {
$scope.name = 'Angular';
$scope.html = 'Hello ';
}]);
</script>

Html:

      
      
1
2
3
4
5
      
      
<div ng-controller="GreeterController">
<input ng-model="name"> <br>
<textarea ng-model="html"> </textarea> <br>
<div compile="html"> </div>
</div>

总之就是用$compile服务创建一个directive ‘compile’,这个complie会将传入的html字符串或者DOM转换为一个template,然后直接在html里调用compile即可。

我基本就是直接copy过来就可以用了,各位看官自便咯~

♦ 本文固定连接:http://gsgundam.com/2014-12-13-angularjs-compile-to-show-dymanic-html-content/

♦ 转载请注明:GSGundam 2014年12月13日发布于 GSGUNDAM砍柴工

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值