How to Write Modular Code with Angular UI-Router & Named Views
Feb 19, 2025 pm 01:19 PMCore 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 withinviews
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'])
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: '/' }); } ]);
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'])
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: '/' }); } ]);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.
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' }, } }); } ]);
(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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

There are three common ways to initiate HTTP requests in Node.js: use built-in modules, axios, and node-fetch. 1. Use the built-in http/https module without dependencies, which is suitable for basic scenarios, but requires manual processing of data stitching and error monitoring, such as using https.get() to obtain data or send POST requests through .write(); 2.axios is a third-party library based on Promise. It has concise syntax and powerful functions, supports async/await, automatic JSON conversion, interceptor, etc. It is recommended to simplify asynchronous request operations; 3.node-fetch provides a style similar to browser fetch, based on Promise and simple syntax

JavaScript data types are divided into primitive types and reference types. Primitive types include string, number, boolean, null, undefined, and symbol. The values are immutable and copies are copied when assigning values, so they do not affect each other; reference types such as objects, arrays and functions store memory addresses, and variables pointing to the same object will affect each other. Typeof and instanceof can be used to determine types, but pay attention to the historical issues of typeofnull. Understanding these two types of differences can help write more stable and reliable code.

Which JavaScript framework is the best choice? The answer is to choose the most suitable one according to your needs. 1.React is flexible and free, suitable for medium and large projects that require high customization and team architecture capabilities; 2. Angular provides complete solutions, suitable for enterprise-level applications and long-term maintenance; 3. Vue is easy to use, suitable for small and medium-sized projects or rapid development. In addition, whether there is an existing technology stack, team size, project life cycle and whether SSR is needed are also important factors in choosing a framework. In short, there is no absolutely the best framework, the best choice is the one that suits your needs.

Hello, JavaScript developers! Welcome to this week's JavaScript news! This week we will focus on: Oracle's trademark dispute with Deno, new JavaScript time objects are supported by browsers, Google Chrome updates, and some powerful developer tools. Let's get started! Oracle's trademark dispute with Deno Oracle's attempt to register a "JavaScript" trademark has caused controversy. Ryan Dahl, the creator of Node.js and Deno, has filed a petition to cancel the trademark, and he believes that JavaScript is an open standard and should not be used by Oracle

CacheAPI is a tool provided by the browser to cache network requests, which is often used in conjunction with ServiceWorker to improve website performance and offline experience. 1. It allows developers to manually store resources such as scripts, style sheets, pictures, etc.; 2. It can match cache responses according to requests; 3. It supports deleting specific caches or clearing the entire cache; 4. It can implement cache priority or network priority strategies through ServiceWorker listening to fetch events; 5. It is often used for offline support, speed up repeated access speed, preloading key resources and background update content; 6. When using it, you need to pay attention to cache version control, storage restrictions and the difference from HTTP caching mechanism.

Promise is the core mechanism for handling asynchronous operations in JavaScript. Understanding chain calls, error handling and combiners is the key to mastering their applications. 1. The chain call returns a new Promise through .then() to realize asynchronous process concatenation. Each .then() receives the previous result and can return a value or a Promise; 2. Error handling should use .catch() to catch exceptions to avoid silent failures, and can return the default value in catch to continue the process; 3. Combinators such as Promise.all() (successfully successful only after all success), Promise.race() (the first completion is returned) and Promise.allSettled() (waiting for all completions)

JavaScript array built-in methods such as .map(), .filter() and .reduce() can simplify data processing; 1) .map() is used to convert elements one to one to generate new arrays; 2) .filter() is used to filter elements by condition; 3) .reduce() is used to aggregate data as a single value; misuse should be avoided when used, resulting in side effects or performance problems.

JavaScript's event loop manages asynchronous operations by coordinating call stacks, WebAPIs, and task queues. 1. The call stack executes synchronous code, and when encountering asynchronous tasks, it is handed over to WebAPI for processing; 2. After the WebAPI completes the task in the background, it puts the callback into the corresponding queue (macro task or micro task); 3. The event loop checks whether the call stack is empty. If it is empty, the callback is taken out from the queue and pushed into the call stack for execution; 4. Micro tasks (such as Promise.then) take precedence over macro tasks (such as setTimeout); 5. Understanding the event loop helps to avoid blocking the main thread and optimize the code execution order.
