It looks like this questions already asked few times but there is no correct answer to it.
my case: i'm loading a template (with html and script) init to div using ajax (not using angular routing temple for some reason).
index.html (main)
<!DOCTYPE html>
<html ng-app="app" ng-controller="AppCtrl">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Web</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
</head>
<body>
<div class="container body-content">
<div class="dynamic-content" >
<!-- Loading content Here -->
</div>
<button ng-click="loadTemplate()">Load Template</button>
</div>
<script>
angular.module('app', [])
.controller('AppCtrl', function ($scope) {
$scope.someData = {};
$scope.loadTemplate = function() {
....
//AJAX to get the templet.html
//and load it into .dynamic-content
//then applying scope();
}
});
</script>
</body>
</html>
template.html (template)
<div ng-controller="TempCtrl">
<h2>About</h2>
<h3>{{total}}</h3>
<p>Testing the total</p>
<button ng-click="update()">Update</button>
</div>
<script>
console.log('begin')
angular.module('app')
.controller('TempCtrl', function ($scope) {
$scope.total = 0;
console.log('inside')
$scope.update = function () {
$scope.total += 1;
};
});
console.log('end')
</script>
when i click the button Load Template
it loads the template.html
file in to container but i'm getting error
Error: [ng:areq] Argument 'TempCtrl' is not a function, got undefined
though its being added to app controllers.
How can i add controllers dynamically and get it work with dynamic html nodes
DEMO HERE https://plnkr.co/edit/EAa9Md36hDzpQ1BgIQKg?p=preview
This blog describes how to fiddle with angular to force it to load additional controllers after it has been bootstrapped:
http://www.bennadel.com/blog/2553-loading-angularjs-components-after-your-application-has-been-bootstrapped.htm
Of course, this is completely unsupported, and could be broken by changes to angular at any time.
But, here is an updated version of your code using this method:
Note that I used jQuery to place the HTML into the DOM, causing the script to execute, then to grab the HTML back out of the DOM so it could be compiled, after which I placed it back in the DOM again.
Also, there is an undefined variable in your template.html, so I updated it to look like this:
Here is a working plunk: http://plnkr.co/edit/cB5N05
Try loading the templates controller in the index.html, instead of in the template.html, that way it is already existing when the markup is looking for it. In index.html script portion:
EDIT: This is when having multiple JS files that reference the app module would be handy, that way each file is owning a controller.
Updated Dave's example with angular components support