Home > Web Front-end > JS Tutorial > How to Write Modular Code with Angular UI-Router & Named Views

How to Write Modular Code with Angular UI-Router & Named Views

Christopher Nolan
Release: 2025-02-19 13:19:14
Original
164 people have browsed it

How to Write Modular Code with Angular UI-Router & Named Views

Core points

  • Angular UI Router is a powerful tool for managing different states in complex web applications, providing more control over each view than native AngularJS routing implementations. It uses dot notation to define child states within the parent state and uses absolute names to control where specific parts of the web application are displayed, enabling modular application design.
  • UI Router allows developers to define a $stateProvider object within views that defines the name of the view and its path to the template. An unnamed view points to the parent state (called relative naming). Named views use the @ syntax to map components to a specific state (called absolute naming).
  • Absolute naming makes the code extremely modular, allowing developers to reuse templates throughout their application or in future projects. It also simplifies the way to use different components of a web application, such as headers and footers, thus saving time and effort.

Writing concise, modular code is one of the most important concepts in web development, especially when teams work together to develop highly complex applications. The Angular framework is designed to create advanced applications that can quickly become very complex, which in turn makes writing modular code even more important. Angular UI Router is a tool that can greatly help you achieve this, and it is designed to help manage the different states of your web application. It gives you complete control over each of its views compared to the native AngularJS routing implementation.

If you have used ui-router before, you may know how to define child states within parent state using dot notation. However, you may not know how the ui-router library handles named views nested within the parent state. This is what I want to explain today.

I will show you how ui-router uses absolute names to fully control where specific parts of a web application appear. This allows you to easily add and remove different interface parts to create modular applications composed of different components. Specifically, I'll show you how to map the navigation bar, some body content, and footer to a specific state. As always, the code for this tutorial is available on GitHub, and you can also find a demo at the end of the article.

Beginner

Take a moment to browse through the files that make up this demo (can be found in the GitHub link above). You can see that we have an index.html file where we have an AngularJS and ui-router library. In this file, we have two ui-view directives that we will insert our content into. Next, we have an app.js file that will contain the code for our Angular application, as well as a templates directory. This directory will be used to accommodate all of our different views. While this folder is not required, it is absolutely in your best interest to use some structure when building your application using Angular. As you can see, I include an assets folder inside the templates folder. This is where I like to store reusable components: header, navigation bar, footer, etc. I think you might find this convention useful because it makes your code extremely modular.

UI-Router

Add dependencies to ui-router

Let's start configuring our application. In our app.js file, we need to add dependencies on ui-router to our main Angular module.

angular.module('app', ['ui.router'])
Copy after login
Copy after login

Configure our route

After completing, we can continue to configure the application's configuration object. Here we will deal with $stateProvider and $urlRouterProvider, so we need to inject them into our configuration objects to use them.

Next, we want to pass the URL of the home page state to $urlRouterProvider.otherwise() so that it maps our application to this state by default. Then we will need to use $stateProvider, which will be what we will deal with in the rest of this tutorial. $stateProvider is a tool provided by ui-router for developers to use when routing applications. The status corresponds to the "position" of the overall UI and navigation aspects in the application. The status describes the UI at that location and its functionality. It works the same way as ngRoute uses routeProvider .

The following is what the app.js file should look like at this time. After configuring the urlRouterProvider, we use $stateProvider to define different states of the application. In this example, we define a state called home and only configure the URL.

angular.module('app', ['ui.router'])
  .config(['$stateProvider', '$urlRouterProvider', 
    function($stateProvider, $urlRouterProvider) {
      $urlRouterProvider.otherwise('/');
      $stateProvider
      .state('home', {
        url: '/'
      });
    }
  ]);
Copy after login
Copy after login

views object

Now that you have set up the base framework, you need to define a $stateProvider object within views. It should follow the URL in the home state. In this object, we will define the names of the views and their template paths. Here you can also define things like controllers; however, I overlooked this for the sake of brevity of this tutorial.

Next, we must first create an unnamed view that will point to the parent state—in this case home. The templateUrl of this unnamed view will fundamentally link the two. This is called relative naming and tells Angular to insert this unnamed view into <div ui-view=""> in our index.html file. Your code should now copy the app.js below.

angular.module('app', ['ui.router'])
Copy after login
Copy after login

As you can see, the unnamed view resolves to main.html, which should be similar to the code below.

angular.module('app', ['ui.router'])
  .config(['$stateProvider', '$urlRouterProvider', 
    function($stateProvider, $urlRouterProvider) {
      $urlRouterProvider.otherwise('/');
      $stateProvider
      .state('home', {
        url: '/'
      });
    }
  ]);
Copy after login
Copy after login
The main.html file contains three named views - nav, body, and footer. In order for these components to appear in the home state, we must define them with absolute naming. Specifically, we must use the

syntax to tell AngularJS applications that these components should be mapped to a specific state. This follows the viewName@stateName syntax and tells our application to use named views from @absolute or a specific state. You can read more about relative names vs absolute names here.

You will see that

is used in our configuration object to make sure that Angular knows that our named view points to our home state. If these absolute names do not exist, the application will not know where to find these named views. That is, check below and see how the application should be routed. @home

angular.module('app', ['ui.router'])
  .config(['$stateProvider', '$urlRouterProvider', 
    function($stateProvider, $urlRouterProvider) {
      $urlRouterProvider.otherwise('/');
      $stateProvider
        .state('home', {
          url: '/',
          views: {
            '': { 
              templateUrl: './templates/main.html' 
            },
          }
        });
     }
   ]);
Copy after login

(CodePen demonstration should be inserted here)

Why this is great

As I said before, absolute naming makes your code extremely modular. In this tutorial, I put all our views in the templates folder. However, you can go a step further and create folders for different views of your application. This allows you to reuse templates throughout the application as well as in future projects! The ui-router library makes it very easy to use different components of a web application, such as the header and footer of a specific view. This will make reusing code in different projects easier and will certainly save you time.

Conclusion

You can use absolute names for more complex, higher-level nesting – this is just an example! Nevertheless, I hope you have a deeper understanding of some of the things that ui-router can achieve. In this article by Antonio Morales, he explains the difference between absolute naming and relative naming, substate, and other aspects of Angular's ui-router library. As always, let me know if you have any questions about this tutorial. I'd love to answer them.

FAQs about writing modular code using Angular UI Router and named views

What is Angular UI Router and how is it different from the standard Angular Router?

Angular UI Router is a flexible routing framework for AngularJS that provides features not found in standard Angular Router. It allows nested views and multiple named views, while the standard Angular Router supports only one view per URL. This makes Angular UI Router a powerful tool for building complex, large-scale applications.

How to set up Angular UI Router in my project?

To set up Angular UI Router, you first need to include the Angular UI Router script in the HTML file. Then, you need to add "ui.router" as a module dependency in your AngularJS application. After that, you can configure your status using $stateProvider and set the default status using $urlRouterProvider.

What are named views in Angular UI Router and how do you use them?

Name view is a feature of Angular UI Router that allows you to assign a name to a view. This allows you to have multiple views per URL, which is very useful in complex applications. To use a named view, you need to include the "ui-view" directive in the HTML file and assign it a name. You can then reference this name in the state configuration.

How to navigate between states in Angular UI Router?

You can use the $state.go() method to navigate between states in Angular UI Router. This method takes the name of the state as a parameter, and optionally takes the parameter object of the state as a parameter. You can also use the ui-sref directive in an HTML file to create links to states.

How to pass parameters to states in Angular UI Router?

You can pass parameters to states in Angular UI Router by including them in the state configuration. You can then access these parameters in the controller using the $stateParams service.

How to deal with state changes in Angular UI Router?

You can use the $stateChangeStart and $stateChangeSuccess events to handle state changes in the Angular UI Router. These events are broadcast on $rootScope and can be listened to in your controller.

How to parse data before activate state in Angular UI Router?

You can parse data before activate state in Angular UI Router using the resolve property in the status configuration. This property is an object that defines any dependencies that need to be parsed before the state is activated.

How to deal with errors in Angular UI Router?

You can use the $stateChangeError event to handle errors in Angular UI Router. This event is broadcast on $rootScope and can be listened to in your controller.

How to use nested views in Angular UI Router?

You can use nested views in Angular UI Router by including the "ui-view" directive in the HTML file and assigning it a name. You can then reference this name in the state configuration.

How to use multiple named views in Angular UI Router?

You can use multiple named views in Angular UI Router by including the "ui-view" directive in the HTML file and assigning it a different name. You can then reference these names in the state configuration.

The above is the detailed content of How to Write Modular Code with Angular UI-Router & Named Views. 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