For this scenario, I have a page of HTML with some AngularJS directives, controllers, etc.
Something like this:
I've faced the same issue, here's what I came up with :
<div id="mController" ng-controller="mainController">
</div>
<div id="ee">
2nd controller's view should be rendred here
</div>
and calling setCnt() function will inject and compile the html, and it will be linked to the 2nd controller:
var app = angular.module('app', []);
function setCnt() {
// Injecting the view's html
var e1 = angular.element(document.getElementById("ee"));
e1.html('<div ng-controller="ctl2">my name: {{name}}</div>');
// Compile controller 2 html
var mController = angular.element(document.getElementById("mController"));
mController.scope().activateView(e1);
}
app.controller("mainController", function($scope, $compile) {
$scope.name = "this is name 1";
$scope.activateView = function(ele) {
$compile(ele.contents())($scope);
$scope.$apply();
};
});
app.controller("ctl2", function($scope) {
$scope.name = "this is name 2";
});
here's an example to test this : https://snippet.run/x4bc
hope this helps.
I had the same problem. This worked for me: https://docs.angularjs.org/api/ng/function/angular.injector
Lets take a small template
var template = '<div ng-controller = "someController">';
template += '<All html you want to add>';
template += '</div>';
Now if you want to add this template you have to do the following two things:
1) Instantiate your controller by $controller
2) Compile your template.
//this creates a new scope
var $scope = $rootScope.$new();
//Controller initialize with $scope
$controller('someController',{$scope,$scope});
var templateEl = angular.element(template);
//Now compile the template with scope $scope
$compile(templateEl)($scope);
angular.element('body').append(templateEL);
I followed this process and it worked for me:
// Some variables
var $controllerElement = angular.element('css-selector-to-the-controller-element');
var $appElement = angular.element('css-selector-to-ng-app-element');
// compiling and applying / digesting the scope.
$appElement.injector().invoke(function($compile) {
var scope = $controllerElement.scope();
$compile($controllerElement)(scope);
scope.$apply();
});
Reference: Angular.injector
I think ng-include might help you, it loads a partial page into the element and compiles and processes it like any other part of your web page.
If This element is the main view of your web app, and you want to load different 'screens' into it, depending on the url, ng-view may come in handy.
You might want to use $compile service. That's what angular do at first place.
And also this guide: http://docs.angularjs.org/guide/compiler