AngularJS 不得不了解的服务 $compile 用于动态显示html内容
2016-05-30 15:17
726 查看
项目中一度纠结与AngularJS如何动态显示不同的html内容。
本来是希望直接使用下面的语句来实现:
但是很尴尬的是,这样不能识别出html标签,而是直接将html里的页面标签全都显示出来了。这当然不是我想要的效果。
谷哥了一番,没想到在官网上就找到了我想要实现的效果,而实现的主角就是今天的 $compile 服务。
https://docs.angularjs.org/api/ng/service/$compile
节选一下关键部分内容,Javascript:
Html:
总之就是用$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砍柴工
本来是希望直接使用下面的语句来实现:
1 | <div> </div> |
谷哥了一番,没想到在官网上就找到了我想要实现的效果,而实现的主角就是今天的 $compile 服务。
https://docs.angularjs.org/api/ng/service/$compile
节选一下关键部分内容,Javascript:
1234567891011121314151617181920212223242526272829303132 | <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> |
12345 | <div ng-controller="GreeterController"> <input ng-model="name"> <br> <textarea ng-model="html"></textarea> <br> <div compile="html"></div></div> |
我基本就是直接copy过来就可以用了,各位看官自便咯~
♦ 本文固定连接:http://gsgundam.com/2014-12-13-angularjs-compile-to-show-dymanic-html-content/
♦ 转载请注明:GSGundam 2014年12月13日发布于 GSGUNDAM砍柴工
相关文章推荐
- 第五章 表单
- 给你一个承诺 - 玩转 AngularJS 的 Promise
- Echart的angularjs封装
- 基于AngularJs + Bootstrap + AngularStrap相结合实现省市区联动代码
- 基于Angularjs实现分页功能
- angularJs中directive的scope ‘@’,‘=’区别
- AngularJs实现分页功能不带省略号的代码
- 数据驱动视图简单实现
- 第四章 内建组件
- AngularJs表单验证实例详解
- angular中的路由简单使用
- AngularJS自定义表单验证
- AngularJS ng-options下拉菜单绑定数值
- AngularJS之Dependency Injection(五)
- AngularJS之Service4
- angularjs对json数据的操作--收货地址列表
- Ext JS与AngularJS
- AngularJS 使用总结
- angularjs 封装百度地图API(实现异步加载)
- 第二章 Typescript