Juriy
Juriy

Reputation: 585

What proper method to route throung chain of states in AngularJS?

I'm implementing signup service, where user suggested to choose three parameters: building (salon), service and company (category). I use ui-router for AngularJS for this task.

I've created prototype with six nested in each other states like so:

angular.module('ngApp', ['ngAnimate', 'ui.router'])
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
  .state('form', {
    url: '/form',
    template: '<div ui-view></div>',
    controller: 'dummyController'
  })
  .state('form.salonChoose' ,{
    url:'/salChoice',
    template: '<button ng-click="changeSalon()">salon 99</button>'
  })
  .state('form.salons', {
    url: '/salons/:salonId',
    template: '<div>{{model.salon}}</div>' +
    '<div ui-view></div>',
    controller: function($scope, $stateParams) {
      $scope.model.salon = $stateParams.salonId;
      location.href = '/#/form/salons/'+$scope.model.salon+'/serviceChoice';
    }
  })
  .state('form.salons.serviceChoice', {
    url:'/serviceChoice',
    template: '<button ng-click="changeService()">service 99</button>'
  })
  .state('form.salons.services', {
    url: '/services/:serviceId',
    template: '<div>{{model.service}}</div>' +
    '<div ui-view></div>',
    controller: function($scope, $stateParams) {
      $scope.model.service = $stateParams.serviceId;
      location.href = '/#/form/salons/'+$scope.model.salon+'/services/'
        +$scope.model.service+'/catChoice';
    }
  })
  .state('form.salons.services.catChoice', {
    url:'/catChoice',
    template: '<button ng-click="changeCat()">cat 99</button>'
  })
  .state('form.salons.services.categories', {
    url: '/categories/:catId',
    template: '<div>{{model.cat}}</div>',
    controller: function($scope, $stateParams) {
      $scope.model.cat = $stateParams.catId;
    }
  });
$urlRouterProvider.otherwise('/form/salChoice');

This approach works in such an implementation. Simple use case to be passed: run app with custom url: #/form/salons/1/services/2/categories/3 and it should will be at state form.salons.services.categories. And prototype works good.

But when I use such an approach in my production app, states going to be not changed after first first change. The difference is that in production nested states had to use same ui-view instead of nested, I think it's tha point, why states not changed.

What the proper way to approach state changing while url having been parsed?

Upvotes: 1

Views: 282

Answers (1)

Abdullah Al Noman
Abdullah Al Noman

Reputation: 2878

For getting a basic idea how states should work you can see this github example.

for changing states use

$scope.changeState = function () {
    $state.go('any.state.you.want.', {param: param});
};

by using something like this

<button ng-click="changeState()">Another state</button>

Upvotes: 1

Related Questions