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的。