Encountered an issue trying to dynamically add generated HTML to the controller's scope and utilize it. I previously posted about a similar topic (generated AngularJS controller usage), but the current task is slightly different now (no need to generate HTML for controller initialization).
The problem I'm facing is that when I dynamically add a controller in the example, I can trigger an alert()
on controller initiation, but not on actions like click_btn(). The same issue arises when adding HTML to a statically defined controller. I've tried both $scope and $rootScope options without any success.
I've experimented with various combinations and variants. Currently, I am encountering an error with
angular.element(document).injector().invoke(function($compile) - Uncaught TypeError: Cannot read property 'invoke' of undefined
.
Below is an example where I am trying to resolve this issue with a simple 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 assistance as I am currently stuck on this issue and it is crucial for progress. Additionally, I must mention that I am unable to insert HTML using angular directives since I need to include variables from the .js file in the var contentString
and Angular must be initialized on page load, preventing me from waiting until the function call to initialize angular.
The actual JS file is much larger and contains numerous functions. This is just a simplified example highlighting the problem.