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

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

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

<div> </div>

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

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

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

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

<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:

<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即可。

原文出处:http://gsgundam.com/2014-12-13-angularjs-compile-to-show-dymanic-html-content/