Can I save a controller in a template file in AngularJS?
I have an index page with the following content: -
<ul>
<li><a href="#">Home</a></li>
<li><a href="#about">About</a></li>
</ul>
<div ng-view></div>
Below is my routing script: -
var app = angular.module('myApp', ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl : 'home.html',
controller : 'homeController'
}).when('/about', {
templateUrl : 'about.html',
controller : 'aboutController'
});
});
Can I save the controller in the templateUrl file? As shown below: -
about.html
<script>
app.controller('aboutController', function($scope) {
$scope.message = 'This is About Us page.';
});
</script>
<h1>About Us</h1>
<p>{{ message }}</p>
Yes, you can save the controller in a template.
index.html
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0-beta.1/angular-route.js"></script>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</head>
<body ng-app="myApp">
<nav class="navbar navbar-default">
<div class="container-fluid">
<div>
<ul class="nav navbar-nav">
<li>
<a href="#home">Home</a>
</li>
<li><a href="#about">About</a></li>
</ul>
</div>
</div>
</nav>
<div ng-view></div>
<script>
var app = angular.module('myApp', ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider
.when('/home', {
templateUrl: 'home.html',
controller: 'homeController'
}).when('/about', {
templateUrl: 'about.html',
controller: 'aboutController'
});
});
app.controller('aboutController', function($scope) {
console.log("aboutController");
$scope.message = 'This is about page.';
});
app.controller('homeController', function($scope) {
console.log("homeController");
$scope.message = 'This is Home page.';
});
</script>
</body>
</html>
home.html and about.html I kept the same
<h3> {{message}}</h3>
You can check out the demo here .