I'm trying to integrate AngularJS to existing web application. Some of data in application is loaded dynamically via $.ajax()
and element.html(data)
. data
can contain html code with javascript code in tag <script>
. This code succesfully loaded by browser, but angular don't see it when I try call $compile()
. How can I fix this?
<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();
} ]);
});
Console log:
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')
- is workaround, because of direct call of html('<script></script>')
don't work in jsffidle.com.