Using ng-view for route templates

Loading

ng-view is a directive in AngularJS used to display the template associated with a route. It is an essential part of Single Page Applications (SPAs), allowing dynamic content loading without refreshing the page.

Why Use ng-view?

Loads templates dynamically based on the current route.
Enables navigation without a full-page reload.
Supports modular and structured application design.
Works with $routeProvider to link views with controllers.


2. Setting Up ng-view

Step 1: Include AngularJS and ngRoute

Before using ng-view, you must include AngularJS and the angular-route.js library.

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular-route.js"></script>

3. Defining Routes with $routeProvider

To use ng-view, you need to configure routes using $routeProvider.

Step 2: Define Routes

Create an AngularJS module and configure the routes.

var app = angular.module("myApp", ["ngRoute"]);

app.config(function($routeProvider) {
$routeProvider
.when("/", {
templateUrl: "home.html",
controller: "HomeController"
})
.when("/about", {
templateUrl: "about.html",
controller: "AboutController"
})
.when("/contact", {
templateUrl: "contact.html",
controller: "ContactController"
})
.otherwise({
redirectTo: "/"
});
});

Explanation:

  • when("/", { templateUrl, controller }) → Loads home.html with HomeController.
  • when("/about", { templateUrl, controller }) → Loads about.html with AboutController.
  • when("/contact", { templateUrl, controller }) → Loads contact.html with ContactController.
  • otherwise({ redirectTo: "/" }) → Redirects unknown routes to the home page.

4. Adding ng-view in index.html

Step 3: Define ng-view

The ng-view directive is placed in the main HTML file where you want the templates to be loaded dynamically.

<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<title>AngularJS Routing with ng-view</title>
</head>
<body>
<nav>
<a href="#!/">Home</a> |
<a href="#!/about">About</a> |
<a href="#!/contact">Contact</a>
</nav>

<!-- This is where the views will be injected -->
<div ng-view></div>
</body>
</html>

5. Creating Route Templates

Each route should have an HTML template.

Step 4: Create home.html

<h2>Home Page</h2>
<p>Welcome to the homepage!</p>

Step 5: Create about.html

<h2>About Us</h2>
<p>Learn more about our company.</p>

Step 6: Create contact.html

<h2>Contact Us</h2>
<p>Get in touch with us.</p>

6. Creating Controllers

Each route is associated with a controller to handle data.

Step 7: Define Controllers

app.controller("HomeController", function($scope) {
$scope.message = "Welcome to the Home Page!";
});

app.controller("AboutController", function($scope) {
$scope.message = "This is the About Page.";
});

app.controller("ContactController", function($scope) {
$scope.message = "Contact us for more information.";
});

Updating Views to Use message from Controllers

Modify the templates to display data dynamically.

<h2>Home Page</h2>
<p>{{ message }}</p>

Now, the text is dynamically loaded from the respective controllers.


7. Passing Parameters to Routes

You can pass dynamic values in the URL.

Step 8: Define a Route with Parameters

.when("/user/:id", {
templateUrl: "user.html",
controller: "UserController"
});

Step 9: Retrieve the Parameter in the Controller

app.controller("UserController", function($scope, $routeParams) {
$scope.userId = $routeParams.id;
});

Step 10: Create user.html

<h2>User Profile</h2>
<p>User ID: {{ userId }}</p>

Example URL:

  • http://example.com/#!/user/5
  • $scope.userId will be 5.

8. Handling Unknown Routes

To prevent errors when navigating to an invalid URL, use .otherwise().

$routeProvider.otherwise({
redirectTo: "/"
});

9. Watching Route Changes ($routeChangeStart)

You can listen to route changes globally.

app.run(function($rootScope) {
$rootScope.$on("$routeChangeStart", function(event, next, current) {
console.log("Route is changing...");
});
});

10. Preloading Data with resolve

You can fetch data before loading the view using resolve.

.when("/profile/:userId", {
templateUrl: "profile.html",
controller: "ProfileController",
resolve: {
userData: function($http, $route) {
return $http.get("api/users/" + $route.current.params.userId);
}
}
});

Retrieve Data in Controller

app.controller("ProfileController", function($scope, userData) {
$scope.user = userData.data;
});

Leave a Reply

Your email address will not be published. Required fields are marked *