Faced a problem with adding dynamically generated HTML to controller's scope and using of it. Here is my other topic(generated AngularJS controller usage) but the task is little but different now(don't need to generate HTML controller's initialization, can be done without it).
The thing is - If i dynamically add controller in this example - i can get alert()
(controller works) on controller's initialization, but not on the click_btn() and other actions.
If i just adding a HTML to statically defined controller - same issue. Don`t get any errors, tried both $scope & $RootScope options.
I tried a lot of combinations & variants. Currently adding here an example with angular.element(document).injector().invoke(function($compile) { - Uncaught TypeError: Cannot read property 'invoke' of undefined
error.
Here is the example where i'm trying to get it work. easy structure and example.
//////////////////////
///Controller Definition (located in different .js file)
//////////////////////
angular.module('MainPage', [])
.controller('Hello', function($scope, $http) {
alert('fsdfsdfsd12121212');
$scope.click_btn = function() {
alert('fsdfsdfsd');
}
});
//////////////////////
///JS FILE from where i need to add HTML to scope and page content
//////////////////////
var contentString =
'<button ng-click="click_btn()">Load Data!</button>';
AddElementAngular(contentString);
function AddElementAngular(html) {
angular.element(document).injector().invoke(function($compile) {
var scope = angular.element(html).scope();
$compile(html)(scope);
$(document.body).append(html);
});
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!doctype html>
<html ng-app="MainPage">
<head>
<title>Hello AngularJS</title>
</head>
<body>
<div ng-controller="Hello">
</div>
</body>
</html>
Seeking for help, so stuck on it, very important thing to continue.
Also have to mention that i can't use iserting HTML by using angular directives, cause i need to put some variables from .js to the var contentString
+ Angular need to be initialized on the page load, so i con't wait before the call of this js func and only then initialize angular.
Actual JS is much bigger and have a lot of func. Here it's just an example for the problem.