Explain the difference between $routeProvider and $stateProvider with example.
-
9Possible duplicate of [What is the difference between $routeProvider and $stateProvider in AngularJs](http://stackoverflow.com/questions/27645202/what-is-the-difference-between-routeprovider-and-stateprovider-in-angularjs) – Martin Oct 15 '15 at 09:29
2 Answers
Basically, $stateProvider
, as the name suggests, allows you to have different states of one route. Meaning that you can give the state a name, different controller, different view without having to use a direct href to a route. Here you can see the differences in the code for $stateProvider
and $routeProvider
:
$routeProvider
.when('/first/', {
templateUrl: 'app/views/first.html',
controller: 'FirstController'
})
});
As you can see, the route definition is the url path in that example.
While, $stateProvider
gives you a lot more flexibility, like in here:
$stateProvider
.state("thisIsTheSecondPage", {
url: "/second/",
templateUrl: '/app/views/second.html',
controller: 'SecondController'
});
With ui-router and $stateProvider
you can use nested views, which are far more complex than regular ngRoute routes.
From a more personal point of view, using <a ui-sref="stateName">
is easier than having to use <a href="#/routename">
.

- 2,555
- 3
- 26
- 35
Generally ui-router works on a state mechanism. for eg: you have a web application that plays video, you have a player which is shared across all the state of the page. Now let's say you just click on some videos to play. In this case, only that video player state should change instead of reloading the full page, (we can see this in music apps like gaana, savan etc.) That can be easily handled by ui-router.
While in ngRoute we just attach the view and the controller.
When ngRoute(angular-route.js) is used, route is configured with $routeProvider. However, when used with ui-router( (angular-ui-router.js)), route is configured with $stateProvider and $urlRouterProvider.
ng-View (developed by the AngularJS team) can be used only once per page, whereas ui-View (3rd party module) can be used multiple times per page.
ui-View is therefore the best option.

- 1,135
- 10
- 23