Using AngularJS injector and $compile service
by Tarek Faham
HTML
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<script>
console.log("Bootstrat Angular");
var app = angular.module("myApp", []);
app.controller('appController', function($scope) {
$scope.testData = 'This is data from the 1st controller appController';
});
app.controller('MyCtrl', function($scope) {
//debugger;
$scope.content = {label:'This is content.label data initilized in the 2nd controller.'};
});
setTimeout(() => {
console.log("Inside setTimeout()");
//debugger;
const appCtrl = document.querySelector("#appCtrl");
const appCtrlElm = angular.element(appCtrl);
const theForm = angular.element(document.querySelector('#myForm'));
const elmHTML = `<label for="customerName">Customer Name:</label><input type="text" id="customerName" name="customerName" ng-model="MyCustomerName" ng-required="myVar" ng-init="MyCustomerName='zxcvf'" style="border: red 2px solid;"/> <span>This field was added during run-time and it will become required if the checkbox below is checked.</span>`;
const elm = angular.element(elmHTML);
const scope = theForm.scope(); //angular.element(elmHTML).scope();
theForm.prepend(elm);
var custAge = document.querySelector("#customerAge");
var custAgeElm = angular.element(custAge);
custAge.setAttribute("ng-required", "true");
const injector = angular.injector(['ng', 'myApp']);
injector.invoke(function($rootScope, $compile, $timeout) {
console.log("Insider injector....");
$compile(elm)(elm.scope()); //$compile(elm)(scope);
$compile(custAgeElm)(custAgeElm.scope());
scope.$digest();
console.log("Done inside injector....");
$timeout(_=>{console.log("Timeout Test")}, 3000);
});
/*injector.invoke(function($rootScope, $compile, $document) {
console.log("Insider injector....");
$compile($document)($rootScope);
$rootScope.$digest();
console.log("Done inside injector....");
});*/
...