2016-10-17 10 views
0

私はAngularJSを既存のWebアプリケーションに統合しようとしています。アプリケーション内の一部のデータは、$.ajax()element.html(data)によって動的にロードされます。 dataには、タグ<script>にjavascriptコードを含むhtmlコードを含めることができます。このコードはブラウザーで正常に読み込まれましたが、角度を表示しても呼び出されません。$compile()これをどうすれば解決できますか?AngularJSでスクリプトタグを使用して動的コンテンツを取得するにはどうすればよいですか?

JSFiddle

<div ng-app="app"> 
    <div id='container'> 

    </div> 
</div> 
var app = angular.module('app', []); 

$(document).ready(function() { 
    var container = $('#container'); 
    var html = ''; 
    html += '<scripttag type="text/javascript">'; 
    html += 'app.controller("TestController", function($scope) {$scope.testVar = "testVal"});'; 
    html += 'console.log("Controller added");'; 
    html += '</scripttag>'; 
    html += '<b ng-controller="TestController">{{testVar}}</b>'; 
    container.html(html.replace(/scripttag/g, 'script')); 

    angular.element(container).injector().invoke([ '$compile', function($compile) { 
      var $scope = angular.element(container).scope(); 
      console.log("Compiling new element..."); 
      $compile(container)($scope); 
      $scope.$apply(); 
    } ]); 
}); 

コンソールログ:

Controller added 
Compiling new element... 
Uncaught Error: [ng:areq] Argument 'TestController' is not a function, got undefined http://errors.angularjs.org/1.2.30/ng/areq?p0=TestController&p1=not%20a%20function%2C%20got%20undefined 

PS html.replace(/scripttag/g, 'script')は - html('<script></script>')の直接呼び出しのjsffidle.comでは動作しないため、回避策です。

答えて

0

問題は、AngularJSアプリケーションがブートストラップされた後、新しいコントローラを定義できないことです。 Description and solution

私の例をhereに修正しました。

app.config(
     function($controllerProvider, $provide, $compileProvider) { 
      app._controller = app.controller; 
      app._service = app.service; 
      app._factory = app.factory; 
      app._value = app.value; 
      app._directive = app.directive; 
      app.controller = function(name, constructor) { 
       $controllerProvider.register(name, constructor); 
       return(this); 
      }; 
      app.service = function(name, constructor) { 
       $provide.service(name, constructor); 
       return(this); 
      }; 
      app.factory = function(name, factory) { 
       $provide.factory(name, factory); 
       return(this); 
      }; 
      app.value = function(name, value) { 
       $provide.value(name, value); 
       return(this); 
      }; 
      app.directive = function(name, factory) { 
       $compileProvider.directive(name, factory); 
       return(this); 
      }; 
     } 
    ); 
関連する問題