javascriptangularjsangular-ui-routerangularjs-routing

What is the difference between $routeProvider and $stateProvider?


Please explain the difference between $routeProvider and $stateProvider in AngularJS.

Which is best practice?


Solution

  • Both do the same work as they are used for routing purposes in SPA(Single Page Application).

    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:-


    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 in a 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 manage nested state & views.

    Pros

    For more Information Angular ui-router

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