I have created a basic AngularJS single page application that uses UI Router to navigate between two views. When the user clicks on the Home link, they should see a line of text. Similarly, clicking on the About link should display some text as well, but its routing is set up to use a separate HTML file as a template:
$stateProvider
.state("home", {
url: "/home",
template: "<h3>This is the Home content</h3>"
})
.state("about", {
url: "/about",
templateUrl: "about.html",
controller: "aboutController"
});
The layout of about.html is very straightforward:
<!DOCTYPE HTML>
<html ng-app="simpleApp">
<head>
<title>About</title>
<script src="aboutcontroller.js"></script>
</head>
<body ng-controller="aboutController">
<h3>{{message}}</h3>
</body>
</html>
The controller script for this view is also quite plain and simple:
console.log("Registered aboutController"); ///////////
angular.module("simpleApp")
.controller("aboutController", ["$scope", function ($scope) {
console.log("Created aboutController"); ///////////
$scope.message = "This is the About content!";
}]);
Upon inspection, I noticed that while the controller script file is being executed, the actual controller itself is never called. Consequently, instead of seeing the expected text, the user encounters:
{{message}}
This seems to be linked to the fact that I am including the controller script in the template file (about.html). The problem disappears when I move the script tag to index.html.
To have a look at a demonstration of my issue and workaround, please visit this Plunker link.
The Core Issue: In this overly simplified scenario, it may seem acceptable to include all controller scripts in the main SPA page. However, for larger web applications with numerous pages and controllers, such an approach may not perform optimally or be easy to maintain.
Hence, what would be the best practice for organizing this setup? How and where should the controller script be included?
Edit: I forgot to mention the error message I encountered (my mistake). With the script tag in about.html, I received an error stating
Argument 'aboutController' is not a function, got undefined
This error appeared immediately after the console message "Registered aboutController". By moving the script tag to include the controller in index.html instead, no error was displayed. This leads me to believe that the controller just isn't readily available to be called in time. Placed in index.html, it is fully registered by the time it's required.