0
我正在嘗試將AngularJS集成到現有的Web應用程序中。應用程序中的一些數據通過$.ajax()
和element.html(data)
動態加載。 data
可以包含代碼爲<script>
的javascript代碼的html代碼。此代碼由瀏覽器成功加載,但當我嘗試撥打$compile()
時,角度不會看到它。我怎樣才能解決這個問題?如何在AngularJS中使用script標籤獲取動態內容?
<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的。