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

标签 javascript angularjs angularjs-factory angularjs-compile

在我的代码中,我需要编译从 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>

最佳答案

就我个人而言,我不会将其放在工厂中,而是添加一个指令来编译代码或在 Controller 中执行它......

如果我理解您想要正确执行的操作,这就是我的建议:

对于静态 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);
        }
    );
};

});

关于javascript - 为什么使用 $compile 会使工厂执行多次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28266557/

相关文章:

javascript - 仅在 IE7 中禁用 JavaScript

javascript - 递增字符串中包含的特定数字

javascript - Angular 应用教程

angularjs - 如何在 Protractor 的 ng-repeat 中找到一个元素

javascript - 使用 yo Angular :factory test fails to load testProvider 创建服务

angularjs - 多个文件中的工厂方法 Angular JS

javascript - 正则表达式在 AngularJS 中不起作用

javascript - 将对象从 tomcat Listener 传递到 Javascript 函数

javascript - 在 Angular 中使用 $parent 是一个好习惯吗?

javascript - 如何使用 AngularJS 设置 HTTP 调用和图像加载的基本 URL