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

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

2016-05-30 15:17 726 查看
项目中一度纠结与AngularJS如何动态显示不同的html内容。

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

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

谷哥了一番,没想到在官网上就找到了我想要实现的效果,而实现的主角就是今天的 $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>
Html:

12345
<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砍柴工
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: