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