文章目录

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

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

1
<div> {{html}} </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 {{name}}';
}]);
</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过来就可以用了,各位看官自便咯~

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

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

♦ 本文版权归作者,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接。

♦ 原创不易,如果页面上有适合你的广告,不妨点击一下看看,支持作者。(广告来源:Google Adsense)

♦ 本文总阅读量