Reputation: 12750
This is my very first AngularJs app and created it after going through many examples on the web but I am doing something wrong here. It is highly likely because files are stored in dedicated folders. The HomeView.html
template gets loaded fine but the controller doesn't. I mean I cannot get greetingMessage
printed in the template. All I see is {{ greetingMessage }}
instead of "Welcome!". What am I missing?
Error
Error: [$controller:ctrlreg] http://errors.angularjs.org/1.6.4/$controller/ctrlreg?p0=HomeController
App Structure
app
conponents
home
HomeView.html
HomeController.js
...
...
index.js
index.html
index.html
<body ng-app="myApp">
<h3>AngularJS</h3>
<hr />
<p><a href="#!">Home</a></p>
<div ng-view></div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-route.min.js"></script>
<script src="index.js"></script>
</body>
index.js
var module = angular.module('myApp', ['ngRoute']);
module.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl : 'components/home/HomeView.html',
controller: 'HomeController'
// I tried -> controller: 'components/home/HomeController'
})
.otherwise({
redirectTo: '/'
});
});
HomeView.html
<div ng-controller="HomeController">
<h4>Home</h4>
<p>{{ greetingMessage }}</p>
</div>
HomeController.js
var module = angular.module('myApp', []);
module.controller('HomeController', [
'$scope',
function(
$scope
) {
$scope.greetingMessage = 'Welcome!';
}]);
Upvotes: 1
Views: 236
Reputation: 1406
You must be attach app file and next attache your controller file in your hoem page or master page.
This example helped you Angular js routing
Upvotes: 0
Reputation: 136184
The main reason is you haven't referred homeController.js
on index.html
, it should place right after index.js
. This will not solve your issue. The other thing I'd like to mention is, you shouldn't be creating myApp
module again while registering your controller with your myApp
module. By declaring new module
will flush out former registered component. So just use module getter like angular.module('myApp')
and append further components to it.
<script src="components/home/HomeController.js">
Code
angular.module('myApp')
.controller('HomeController', [ '$scope',
function($scope) {
$scope.greetingMessage = 'Welcome!';
}
]);
Upvotes: 2