angularjsHow can I set up routes in AngularJS?
To set up routes in AngularJS, you need to use the $routeProvider
service. This service allows you to define the routes for your application, and map them to controllers and views.
Here is an example of how to set up routes:
angular.module('myApp', ['ngRoute'])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.when('/about', {
templateUrl: 'views/about.html',
controller: 'AboutCtrl'
})
.otherwise({
redirectTo: '/'
});
});
In this example, we have defined two routes: /
, which is the main page of the application, and /about
, which is an about page. For each route, we have specified a templateUrl
which is the path to the HTML template for that page, and a controller
which is the controller associated with that page. Finally, we have specified an otherwise
route which will redirect to the main page if a route is not found.
Code explanation
-
angular.module('myApp', ['ngRoute'])
: This creates an AngularJS module namedmyApp
, and includes thengRoute
module, which provides the$routeProvider
service. -
.config(function ($routeProvider)
: This defines the configuration function for the module, and provides the$routeProvider
service. -
.when('/', { ... })
: This defines a route for the/
path, and specifies thetemplateUrl
andcontroller
for that route. -
.when('/about', { ... })
: This defines a route for the/about
path, and specifies thetemplateUrl
andcontroller
for that route. -
.otherwise({ ... })
: This defines a route which will be used if none of the other routes match. In this case, it will redirect to the/
path.
Helpful links
More of Angularjs
- How can I use Angular to zoom in and out of a div?
- How can I become an Angular expert from a beginner level?
- How do I create a yes/no dialog box using Angular?
- How can I use AngularJS with Visual Studio Code?
- How do I use the AngularJS router?
- How do I use Angular to zip files?
- How do I use Angular Zone to detect and run Angular change detection?
- How can I prevent XSS attacks when using AngularJS?
- How can I use query parameters in an AngularJS application?
- How can I use AngularJS to create a zone in my software development project?
See more codes...