2

Is it possible to have routing as follows in angular?
I'm using ui-router for routing, Angular version is 1.4 FYI

.state('home', {
  url: '/:city',
  controller: 'HomeCtrl',
  templateUrl: 'templates/home.html'
}) 

.state('about', {
  url: '/about',
  controller: 'AboutCtrl',
  templateUrl: 'templates/about.html'
})

.state('login', {
  url: '/login',
  controller: 'LoginCtrl',
  templateUrl: 'templates/login.html'
})

When I tried this way angular is considering both /about and /login as home state and giving me "about" and "login" in state params is there anyway to override this to have urls as specified?

1 Answer 1

2

Just define your static routes before home state, here's a demo

var app = angular.module('app', ['ui.router']);
app.config(function($stateProvider, $urlRouterProvider) {
  // what's the initial route? for the sake of example, it's `/almaty`
  $urlRouterProvider.otherwise("/almaty");
  $stateProvider
    .state('about', {
      url: '/about',
      template: '<h1>about</h1>'
    })
    .state('login', {
      url: '/login',
      template: '<h1>login</h1>'
    })
    .state('home', {
      url: '/:city',
      controller: function($scope, $stateParams) {
        $scope.stateCity = $stateParams.city
      },
      template: '<h1>city - {{stateCity}}</h1>'
    })
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://unpkg.com/[email protected]/release/angular-ui-router.min.js"></script>

<div ng-app="app">
  <ul>
    <li>
      <a href="#/almaty">city Almaty</a>
    </li>
    <li>
      <a href="#/about">about</a>
    </li>
    <li>
      <a href="#/login">login</a>
    </li>
  </ul>
  <div ui-view></div>
</div>

Sign up to request clarification or add additional context in comments.

2 Comments

Forgot about the ui-router states order :) Removed my answer and up-voted yours
Thankyou for the simplest answer. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.