0

私のコードでは、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>

4

1 に答える 1

0

個人的には、それをファクトリに入れませんが、コードをコンパイルするか、コントローラーで実行するためのディレクティブを追加します....

あなたが正しくやろうとしていることを理解したら、これは私が提案することです:

静的な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);
        }
    );
};

});

于 2015-02-01T19:21:52.983 に答える