Component Based Architecture In AngularJs Using UI-Router

Thejeshwar Reddy
|
5
min read
Component Based Architecture In AngularJs Using UI-Router

There's no doubt in the fact that one who is going to start writing a new app today would not be choosing angularJs framework, however thousands of AngularJs applications do exist as many companies who have started off with it use it till today, safe to say AngularJs isn’t going anywhere.

Most of the application examples I see in AngularJs are mostly in a controller-view structure (using ngRoute), we can achieve better functionality when we couple components and ui-router modules, Developers from later frameworks (Angular, Vue, React) would be familiar with this architecture, It gives powerful functionality compared to ngRoute. Let's get started.

To access the full source code, click here.

What is a UI-ROUTER?

UI Router is a routing framework for AngularJS, which allows you to organize the parts, or components of your interface into a state machine. Unlike the ngRoute module, which is organized around URL routes.

Let us take a small example of contact directory app:

1. List of contacts (contactsComponent)

2. Messages for a contact selected (messagesComponent)

3. Detail about a contact selected (detailsComponent)

UI-Router(state) Vs Ng-Route

In state approach, the views are tied to the state, whereas in ng-route, views are tied to the browser url. Here's an example:

a. ngRoute

Consider the route transition from /contacts?contactId=1 to /contacts?contactId=2.

When the transition happens browser considers this as a complete url change and because the browser considers this as a new url even the contactsList may be re rendered(and apis required to load the contacts list) along with the messages and details which is not required(Extra load).

b. UI-Router

Now lets consider the same case with ui-router — component

Image for post
Image for post

In this case we can selectively load only the messages component and details component when ever the contactId changes, avoiding to re render the contacts component ie you can load only the components tied to that particular state avoiding to load the parent components.

Functionality provided by UI-Router

1. States

2. nested states, nested views (In ngRoute only one view is present that is why even param change is considered as a route change and whole view is re rendered)

3. named views

4. transition hooks (not discussed in this article very useful though)

UI-Router states

1. A state is a particular position in entire navigation system of the application.

2. In UI-Router consider the entire application as a tree of states, only one state can be active at a time

3. You can move from any state to any other state in the state tree

UI-Router nested views

1. A nested view is a child view to a particular state,

example-

/home/info

/home/list

here both info and list are the child views(nested views) of /home, and you can activate any one state and the corresponding view is rendered

UI-Router named views

1. Lets say you have two components both should be rendered for a particular state then we need to name the views so that we can configure to say which component should be rendered in which view

example -

/contacts/{contactId} which is a child state to /contacts

here we have two components — messagesComponent and detailsComponent which need to be rendered then we name each nested view with a name

name of a view is given using name attribute, something like this,

<ui-view name=”messageView” ></ui-view>

<ui-view name=”detailsView”></ui-view>

and then configure to render which component in which view, like this,

views: {

‘messageView@contacts’: ‘messagesComponent’,

‘detailsView@contacts’: ‘detailsComponent’

},

Components - What, When, Why, and How

What is a component in AngularJs?

1. Component is a way to create re-usable isolated entities.

2. A component is same as a directive(The main difference is that it is always isolated scope unlike a directive where u can choose whether it should be isolated or not)

3. The reason a component is always isolated is cause,

In a large application when $scope Inheritance or watchers are in play there will be problems where it will be difficult to know which part of the application has actually updated a particular variable, here components works better(isolated scope).

When should a component be used

1. A component should be used when you are writing an application in the component architecture(I would say if the application is not a component based one no need of components you can use directives for other purposes).

2. A component is restricted to 'E', so if u want a directive which needs to be triggered by Attribute or Class use directives instead.

Why a component should be used

1. Components have a well-defined lifecycle hooks

2. Components only control their own View and Data

3. simpler configuration than plain directives

4. optimised for component-based architecture

How a component is created

angular.module(‘angularApp’).component(‘messagesComponent’, { templateUrl: ‘/client/components/messages/messages.html’, controller: messagesController,

bindings: {

   contact: ‘<’

 }

});

Lets see some implementation of contacts directory app (mentioned above),

We have three components (refer the component hierarchy image above)

1. contacts component

2. messaging component

3. details component

Adding routes and states

1. Lets add /contacts route and name the state as contacts

//app.js

var app = angular.module('angularApp', ['ui.router']);

app.config(function ($stateProvider, $urlRouterProvider) {

$stateProvider.state({

 name: 'contacts',

 url: '/contacts',

 component: 'contactsComponent'

});

$urlRouterProvider.otherwise('/contacts');

});


// main.html

<ui-view></ui-view>

Explanation

a. we have created a <ui-view/> in main.html which is the main view of whole application.

b. When contacts state is active then the contactsComponent is rendered in the <ui-view/> of main.html

2. Now lets add a child route to /contacts with named views

//app.js

$stateProvider.state({

name: 'contacts.person',

url: '/{contactId}',

views: {

 'messageView@contacts': 'messagesComponent',

 'detailsView@contacts': 'detailsComponent'

},

resolve: {

 contact: function (contactsFactory, $transition$) {

    return

    contactsFactory.getContact($transition$.params().contactId-1);

 }

}

});


//contacts.html

<ui-view name="messageView"></ui-view>

<ui-view name="detailsView"></ui-view>

Explanation

a. we have created contacts.person which is a syntax(dot operator) to append child state to a parent state so now person is a child state to contacts.

b. we have created two <ui-view/> tags and have given each view a name

c. now in views property we have mentioned

‘messageView@contacts’: ‘messagesComponent’,

which is to say to render messagesComponent in the view with name messageView.

d. so now when person state is activated then the components are rendered to the respective views mentioned in views property

3. How to navigate to a particular state

Through controller

$state.go(‘contacts.person’, { contactId: contact.id });

Through view

<a ui-sref="contacts.person({ contactId: {{contact.id}} })">Contacts</a>

Conclusion

I would suggest to build the application in this model itself, for better performance, fast and clean application.

1. Component support has been added in AngularJs from version 1.5, probably as the new frameworks follow the component architecture by default.

2. UI-Router has been developed by Angular team itself so you can depend on it, not worrying about the quality of the library

Repo for the complete source code

https://github.com/Thejeshwar-Reddy/AngularJs-UI-Router

Tags
No items found.
About Engati

Engati powers 45,000+ chatbot & live chat solutions in 50+ languages across the world.

We aim to empower you to create the best customer experiences you could imagine. 

So, are you ready to create unbelievably smooth experiences?

Check us out!