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 thengRoutemodule, which provides the$routeProviderservice.
- 
.config(function ($routeProvider): This defines the configuration function for the module, and provides the$routeProviderservice.
- 
.when('/', { ... }): This defines a route for the/path, and specifies thetemplateUrlandcontrollerfor that route.
- 
.when('/about', { ... }): This defines a route for the/aboutpath, and specifies thetemplateUrlandcontrollerfor 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 become an Angular expert from a beginner level?
- How can I use Angular to zoom in and out of a div?
- How can I use AngularJS to create a zone in my software development project?
- How can I create an editable AngularJS application?
- How do I use Angular with YAML?
- How can I use AngularJS with Visual Studio Code?
- How do I use Angular Zone to run my code?
- How do I use Angular to zip files?
- How can I prevent XSS attacks when using AngularJS?
- How do I use an AngularJS CDN?
See more codes...