2016-03-29 36 views
2

AJAXを介して動的なHTMLコンテンツを読み込み、角度指示文が含まれているため、コンパイルします。動的テンプレートを角度の外側からコンパイルするには?

私は、角度コントローラまたはディレクティブのスコープにすることなく、角度を使用して助ける方法を使用しています this classいる

<!DOCTYPE html> 
<html> 
    <head> 
     <title>AngularJS Test</title> 
    </head> 
    <body> 
     <div id="contents"><!-- content --></div> 
     <script src="js/angular.js"></script> 
     <script type="text/javascript"> 
      $(document).ready(function(){ 
       $.get("http://fuiba.com/test/index.html", function(data) { 
        $("#result").html(data); 
        AngularHelper.Compile('$("#result")', data); 
       }); 
      }); 
     </script> 
    </body> 
</html> 

var AngularHelper = (function() { 
    var AngularHelper = function() { }; 

    /** 
    * ApplicationName : Default application name for the helper 
    */ 
    var defaultApplicationName = "MyApp"; 

    /** 
     * Compile : Compile html with the rootScope of an application 
     * and replace the content of a target element with the compiled html 
     * @$targetDom : The dom in which the compiled html should be placed 
     * @htmlToCompile : The html to compile using angular 
     * @applicationName : (Optionnal) The name of the application (use the default one if empty) 
     */ 
    AngularHelper.Compile = function ($targetDom, htmlToCompile, applicationName) { 
     var $injector = angular.injector(["ng", applicationName || defaultApplicationName]); 

     $injector.invoke(["$compile", "$rootScope", function ($compile, $rootScope) { 
         //Get the scope of the target, use the rootScope if it does not exists 
      var $scope = $targetDom.html(htmlToCompile).scope(); 
      $compile($targetDom)($scope || $rootScope); 
      $rootScope.$digest(); 
     }]); 
    } 
    return AngularHelper; 
})(); 

その後、私は私のjQueryの成功AJAXリクエストの後にそれを使用します

しかし、私はこのエラーを受け取ります(codepenを参照してください):

$targetDom.html is not a function

+1

。 '$("#result ") '、data);' '$("#result ")'')を引数 '$ taに渡していますrgetDom'を呼び出すことでjQueryオブジェクトのように動作します。 Stringクラスには、このようなメソッドはありません。 –

+0

@RytisAleknaあなたとMiTaのおかげで問題は解決しましたが、別のエラーが発生します。この[codepen](http://codepen.io/anon/pen/xVLVVv)を参照してください。 –

答えて

1

あなたは、AngularHelper.Compile機能に最初のパラメータとしてではない文字列をDOM要素を渡す必要が

ので

AngularHelper.Compile($("#result"), data);

ないこのライン `AngularHelperで

AngularHelper.Compile('$("#result")', data);

+0

ありがとう@MiTa!問題は解決しましたが、別のエラーが表示されます: 'Module 'MyApp'は利用できません!モジュール名のスペルが間違っているか、モジュール名を読み込めませんでした。 '[codepen](http://codepen.io/anon/pen/xVLVVv) –

+1

41行目を見てください' angular.module( 'MyApp') 'あなたはモジュールを登録すると、依存関係を2番目の引数として指定します。 ( 'MyApp'、[]) ' – MiTa

+0

この_AngularHelper_クラスはなぜ私にとってではなく他の人にとって完璧に動作するのか分かりません。別のエラーが出ます: '$ targetDom.html(...)。scopeは関数ではありません。 '私はそれを解決しようとします!ありがとうございました!! –

関連する問題