arjun arjun - 2 months ago 11
Javascript Question

What is the difference between $routeProvider and $stateProvider in AngularJs

Please explain the difference between

$routeProvider
and
$stateProvider
in AngularJs.

Which is best practice.

Answer

Both do same work as like they used for routing purpose in SPA.

1. Angular Routing - per $routeProvider docs

URLs to controllers and views (HTML partials). It watches $location.url() and tries to map the path to an existing route definition.

HTML

<div ng-view></div>

Above tag will render the template from the $routeProvider.when() condition which you had mentioned in .config (configuration phase) of angular

Limitations:-

  • The page can only contain single ng-view on page
  • If your SPA has multiple small components on page which you wanted to render based on some condition, In such scenario $routeProvider fails.(for achieving the same we need to go for directive like ng-include, ng-switch, ng-if, ng-show actually which looks bad to have them in SPA)
  • You can not relate between two routes like parent and child relationship.
  • You cannot show and hide a part view based on url pattern.

2. ui-router - per $stateProvider docs

AngularUI Router is a routing framework for AngularJS, which allows you to organize the parts of your interface into a state machine. UI-Router is organized around states, which may optionally have routes, as well as other behavior, attached.

Multiple & Named Views

Another great feature is the ability to have multiple ui-views view per template.

While multiple parallel views are a powerful feature, you'll often be able to manage your interfaces more effectively by nesting your views, and pairing those views with nested states.

HTML

<div ui-view>
    <div ui-view='header'></div>
    <div ui-view='content'></div>
    <div ui-view='footer'></div>
</div>

The majority of ui-router's power is it can manages nested state & views.

Pros

  • You can have multiple ui-view on single page
  • various view can be nested in each other and maintain by defining state in routing phase.
  • We can have child & parent relationship here, simply like inheritance in state, also you could define sibling states.
  • You could change the ui-view="some" of state just by using absolute routing using @ with state name.
  • Other way you could relative routing using only @ to change ui-view="some", This will replace the ui-view rather than checking it is nested or not.
  • Here you could use ui-sref to create a href URL dynamically on the basis of URL mentioned in a state, also you could give a state params in the json format.

For more Information Angular ui-router

For better flexibility with various nested view with states, I'd prefer you to go for ui-router

Comments