In AngularJS I'm trying to manually load a template that uses a predefined controller.
I call a WebApi to get a list of available templates. When this list is received I should load each template onto the page. Each template also uses an AngularJS controller so the connection between the template and the preloaded controller must work.
After some googling I ended up on this previous (and somewhat old) question: AngularJS Manually Render Controller and Template
It seems to do exactly what I want, but it has a directive that uses more parameters than I need. Also, I don't have directives for my templates. I just can't wrap my head around how to get it to do what I want.
How can I get ExampleTemplateToLoad.html
to be loaded by code, inserted into div#LoadedTemplates
while functioning like a normal template using a controller?
main.js
var myApp = angular.module('myApp', [.....]);
myApp.config(function($routeProvider) {
$routeProvider.when('/', { templateUrl : '/mainTemplate.html' });
});
myApp.controller('mainController', function ($scope, $http) {
$http.get('/api/getListOfTemplateScripts').success(function (data) {
// This returns a list of scripts that should be loaded
// Scripts are loaded using https://github.com/ded/script.js
// These scripts show up in "Sources" in Chrome Developer Tools,
// and any syntax errors in these scripts are also displayed in
// the console, so the script is definitely loaded
angular.forEach(data, function (scriptFile, key) {
$script(scriptFile, function() {
console.log(scriptFile + " loaded");
});
});
})
.then(function() {
$http.get('/api/getListOfTemplate').success(function (data) {
// This returns a list that includes ExampleTemplateToLoad.html
// The template should then be loaded into div#LoadedTemplates
angular.forEach(data, function (templateFile, key) {
// This is logged *after* "scriptToLoad loaded" in the console
console.log('Loading template ' + templateFile);
});
});
});
});
mainTemplate.html
<div ng-controller="mainController">
<div id="LoadedTemplates"></div>
</div>
ExampleTemplateToLoad.html
<div ng-controller="loadedTemplateController">
<!-- Do whatever the template needs to do, using variables defined
in $scope as it would normally do -->
</div>
ExampleTemplateControllerToLoad.js
myApp.controller('loadedTemplateController', function ($scope, $http) {
});