Matoy
Matoy

Reputation: 1808

refactor angular-route to angular-ui-router

I've created a single page application using ngRoute like so:

index.html (ngRoute)

var smallTalkzModel = angular.module('smallTalkzModel', ['ngRoute']);
smallTalkzModel.config(function($routeProvider) {

    $routeProvider
    .when('/', {
      templateUrl : 'components/login/loginView.html',
      controller  : 'loginController'
    }) 
    .when('/chat', {
      templateUrl : 'components/chat/chatView.html',
      controller  : 'chatController'
    });
  }).run(function ($rootScope) {

    // App is loading, so set isAppLoading to true and start a timer
    console.log($rootScope);
    $rootScope.isAppLoading = true;

  });;

small-talkz.model.js (ngRoute)

 <div ng-app="smallTalkzModel" >
    <div ng-view>
    </div>

 </div>

Then I heard that it is better to use ui.router because it is a 3rd party which have more capabilities and can does everything that ngRoute does and more and will be supported in future version of angular js...

So, I tried to refactore my code into the code below. which does not work...

Can anyone tell me why? I did not use ng-surf because I don't have any links into my html. I get to them by localhost:3000/somePage and not by navigation...

index.html (ui.router)

<div ng-app="smallTalkzModel" class="loader">
    <div ui-view>
    </div>
</div>

small-talkz.model.js (ui.router)

var smallTalkzModel = angular.module('smallTalkzModel', ['ui.router']);
smallTalkzModel.config(function($stateProvider, $urlRouterProvider) {

  $stateProvider
  .state('login', {
    url: '/',
    templateUrl : 'components/login/loginView.html',
    controller  : 'loginController'
  }) 
  .state('chat', {
    url: '/chat',
    templateUrl : 'components/chat/chatView.html',
    controller  : 'chatController'
  });
});;

Upvotes: 0

Views: 80

Answers (2)

Manu
Manu

Reputation: 10964

Expecting that you have included the library ui-router.js in your project. Code looks fine. One thing i think might me causing issue is to define the route when none of the states defined by you matches the state of application. Use otherwise option for that as below:

$urlRouterProvider.otherwise('/');

Code should look like:

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

  $stateProvider
  .state('login', {
    url: '/',
    templateUrl : 'components/login/loginView.html',
    controller  : 'loginController'
  }) 
  .state('chat', {
    url: '/chat',
    templateUrl : 'components/chat/chatView.html',
    controller  : 'chatController'
  })
  $urlRouterProvider.otherwise('/');

});

Upvotes: 1

shan kulkarni
shan kulkarni

Reputation: 855

angular-ui-router is based on states. If you want to go from one state to another then you have to use "ui-sref" or "$state.go()"

for example to go to your chat page (State), use:

<a ui-sref="chat">to go chat page</a>

Upvotes: 1

Related Questions