angularjsangular-ui-routerng-view

Transition from ng-view to ui-view


I have an older app (Angular 1.5.3) and I would like to take advantage of angular-ui-router and components for a few of my pages.

Is it possible to use the old routeProvider in conjunction with the stateProvider that ui-router provides?

IE I would like to transition a few pages to use components here and there as I get time, while leaving the rest.

I am pretty sure using ng-view and ui-view I am having a hard time getting that to work (probably cause you are not supposed to do that). Does that mean I have to transition my entire project from routeProvider to stateProvider all at once?


Solution

  • Is it possible to use the old routeProvider in conjunction with the stateProvider that ui-router provides?

    Short answer

    No. Similar structure but different syntax

    Long answer

    No, but ... You can easily convert ng-view to ui-view a.e. from $routeProvider to $stateProvider.

    Consider example ng-view:

    $routeProvider  
      .when('/Book/Add', {
        template: '<div class="box" ng-class="classname">Add</div>',
        controller: function($scope) {$scope.classname="add"}
      })
      .when('/Book/Error', {
        templateUrl : 'error.html',
        controller: 'ErrorController'
      })
      .otherwise({redirectTo: '/Book/Error'});
    

    Consider example ui-view:

     $stateProvider
     .state('book', {
                     url: '/Book',
                     abstract: true,
                     templateUrl: 'views/Book.html'
                    })
    .state('book.add', {
                        url: '/inbox',                    
                        template: '<div class="box" ng-class="classname">Add</div>',
                        controller: function($scope) {$scope.classname="add"}                     
                    })
    .state('book.error', {
                        url: '/Error',                    
                        templateUrl : 'error.html',
                        controller: 'ErrorController'                   
                    })
    
    $urlRouterProvider.otherwise(function ($injector, $location) {
               return '/Book/Error';
              });
    

    Keep in mind that routing syntax will change too.

    For example:

     if ($state.current.name === 'login') {
          $state.go('book.add', {});
     }
    

    Instead <a href="/Book/Add">Add</a> we will write <a ui-sref="book.add">Add</a>

    And so on ......


    As you can see, the syntax is a bit similar. I'm sure you will find a lot of references about power of $stateProvider. For example https://stackoverflow.com/a/21024270/1631379

    Hope I answered on your question