Home > Web Front-end > JS Tutorial > An Introduction to the Futuristic New Router in AngularJS

An Introduction to the Futuristic New Router in AngularJS

Jennifer Aniston
Release: 2025-02-20 09:28:10
Original
271 people have browsed it

An Introduction to the Futuristic New Router in AngularJS

Key Points

  • AngularJS is enhancing its routing capabilities with a new router currently being developed in Angular 2 and will be backported to Angular 1.4. This router solves the limitations of the ngRoute module, such as the inability to support complex scenarios such as nested views, parallel views, or view sequences.
  • The new router simplifies routing creation, allows navigation between templates and enables management of multiple parallel views on the page. It also provides flexible control over the component life cycle, allowing interception and control navigation.
  • Although still under development, the new router is worth trying because it promises to simplify the transition to Angular 2 and is designed to handle complex application scenarios efficiently.

AngularJS is one of the most popular JavaScript MV* frameworks and is widely used to build single-page applications (SPAs). One of the most challenging features in a SPA is routing. Client routing involves changing part of the view and creating entries in the browser navigation history. As a fully functional client framework, AngularJS has always supported routing through the ngRoute module. While this is good enough for basic routing, it does not support more complex scenarios such as nested views, parallel views, or view sequences.

A new Angular 2 router is currently under development and will be backported to Angular 1.4. In this article, we will learn how to define a route using a new router and how it solves some of the problems that ngRoute cannot solve.

As mentioned before, development of the new router is still underway at the time of writing, and some APIs may change later. The Angular team has not named the new router yet, so it is currently called the future router.

Limitations of ngRoute

ngRoute is not created with complex enterprise applications in mind. I have personally seen some applications where certain parts of the page need to be loaded in several steps. Such applications can be built using ngRoute, but it is nearly impossible to have a URL state for every change applied to the view.

The

ng-view directive can only be used once within an instance of the ng-app directive. This prevents us from creating parallel routes because we cannot load two parallel views at the same time.

View templates rendered inside ng-view cannot contain another ng-view directive. This prevents us from creating nested views.

The new router solves these problems and provides a flexible way to define and use routing. The new router also uses the "Controller as" syntax. I highly recommend using the "Controller as" syntax because this is one of the conventions you should follow today in preparing Angular 2.

Create a simple route

The new router is created with Angular 2 in mind. Angular 2 will simplify dependency injection by eliminating the module configuration phase, which means we don't need to write configuration blocks to define routes - we can define them anywhere.

Each route to be added to a new router contains two parts:

  • path: URL of the routing template
  • component: A combination of templates and controllers. By convention, both controller and template must be named after components

Routing is configured using the $router service. Since $router is a service, we can define routes anywhere in the application (except in the provider or configuration block). However, we need to make sure that the code blocks that define the route are executed immediately after the application loads. For example, if the route is defined in the controller (we will do so soon), the controller must be executed when the page loads. If they are defined in a service, the service method must be executed in the run block.

Navigate between templates

Let's define two simple routes and use a new router to navigate between them. If you want to continue using this code, you need to get a copy of your new router. Please tell me how to do it.

You can install a new router on a per project basis via npm.

mkdir new-router && cd new-router
npm install angular-new-router
Copy after login
Copy after login

This will create a folder named node_modules in your project directory. The new router can be found in node_modules/angular-new-router/dist/router.es5.min.js. Include it in your project after AngularJS itself.

First, let's define a module and configure the route:

angular.module('simpleRouterDemo', ['ngNewRouter'])
  .controller('RouteController', ['$router', function($router){
    $router.config([
      { path:'/', redirectTo:'/first' },
      { path:'/first', component:'first' },
      { path:'/second/:name', component:'second' }
    ]);

    this.name='visitor';
  }])
Copy after login
Copy after login

The controller in the above code snippet defines three routes. Note that the root route redirects to our first template and the third route accepts parameters from the URL. As you can see, the syntax for the specified parameter is the same as ngRoute.

As mentioned earlier, each component requires a corresponding view template and a controller. By convention, the name of the controller should be the component name suffixed with "Controller" (firstController and secondController in our example). The name of the view template must be the same as the name of the component. It must also be in a folder with the same name as the component, within a folder named components. This will give us:

<code>projectRoot/
  components/
    first/
      first.html
    second/
      second.html</code>
Copy after login

These conventions can be covered by $componentLoaderProvider. We'll see an example later, but let's stick with these conventions for now.

The following is a view of the components first and second used above. We define them inline using the ng-template directive (so we can recreate a runnable demo), but ideally they should be in a separate HTML file:

<🎜>

<🎜>
Copy after login

Because the view is very simple, the controller is also very simple:

angular.module('simpleRouterDemo')
  .controller('FirstController', function(){
    console.log('FirstController loaded');
    this.message = 'This is the first controller! You are in the first view.';
  })
  .controller('SecondController', function($routeParams){
    console.log('SecondController loaded');
    this.message = 'Hey ' + $routeParams.name + 
      ', you are now in the second view!';
  });
Copy after login

Since both controllers are created for use with the "Controller as" syntax, they do not accept $scope. $routeParams The service is used to retrieve the values ​​of parameters passed in the route.

Now, we need to load this controller to register the route:

mkdir new-router && cd new-router
npm install angular-new-router
Copy after login
Copy after login

Finally, we need to link these routes and load them into the page. The new router brings the ng-link directive and the ng-viewport directive, which link the view and load the templates respectively. The ng-viewport directive is similar to ng-view; it is a placeholder for a part of the application that loads dynamically based on the routing configuration.

The following code snippet shows how these instructions are used:

angular.module('simpleRouterDemo', ['ngNewRouter'])
  .controller('RouteController', ['$router', function($router){
    $router.config([
      { path:'/', redirectTo:'/first' },
      { path:'/first', component:'first' },
      { path:'/second/:name', component:'second' }
    ]);

    this.name='visitor';
  }])
Copy after login
Copy after login

(Subsequent sections, regarding parallel views, component life cycle management and conclusions, due to space limitations, they are omitted here. The remaining part of the original text can be rewrited as needed.)

The above is the detailed content of An Introduction to the Futuristic New Router in AngularJS. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template