繁体   English   中英

为什么使用$ compile使工厂执行多次

[英]Why does using $compile make factory execute multiple times

在我的代码中,我需要从javascript回调函数内部编译从另一个api返回的html。

以下是我的代码的简化版本。 我正在使用一种工厂方法,该方法使用$ compile和$ rootScope重新编译任何元素。

这种设置的奇怪之处在于,编译功能使数据工厂多次执行。 这是什么原因呢? 还有任何建议或这种动态html编译方法中的缺陷吗?

这是一个塞子链接http://plnkr.co/edit/D32kCS4BkslvpBsRtFoS

 var app = angular.module('mainApp', []); app.factory('CompileDirective', function($compile, $rootScope) { function compileApp() { $compile($("[ng-app='mainApp']"))($rootScope); } return { compileApp: compileApp }; }); app.factory('data', function() { alert("run"); return "data"; }); app.directive('testDirective', function(data) { return { restrict: 'E', templateUrl: 'tpl.html' }; }); function addDirective() { $('#container').append('<test-directive></test-directive>'); callback(); } function callback() { alert('callback called'); angular.injector(['ng', 'mainApp']).get("CompileDirective").compileApp(); } 
 <script data-require="angular.js@1.3.7" data-semver="1.3.7" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.7/angular.js"></script> <script data-require="jquery@*" data-semver="2.1.1" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <body ng-app="mainApp"> <script type="text/ng-template" id="tpl.html"> {{ "hello" + "world"}} </script> <h1>Hello Plunker!</h1> <input type="button" value="Add Directive" onClick="addDirective()" /> <div id='container'> <test-directive></test-directive> </div> </body> 

我个人不会将它放在工厂中,而是添加一条指令来编译代码或在控制器中执行...。

如果我了解您要正确执行的操作,则建议这样做:

对于静态html,您已经有了ng-bind-html指令...,如果您需要动态的,只需创建一个像这样的指令

angular.module('app',[]).directive('ngHtmlCompile',function ($compile) {
  return function(scope, element, attrs) {
      scope.$watch(
        function(scope) {
           // watch the 'compile' expression for changes
          return scope.$eval(attrs.ngHtmlCompile);
        },
        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);
        }
    );
};

});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM