2

ui-router 0.2.11 / AngularJS 1.3.0

I struggle to understand why my $stateChangeSuccess event handler in BarCtrl is not triggered on #/foo/bar. It is triggered on #/bar.

#/foo/bar -> Console: foo
#/bar -> Console: bar

What I'm trying to achieve is that on #/foo/bar first FooCtrl's handler is triggered and then BarCtrl's:

foo
bar

My code:

var app = angular.module('foobar', ['restangular', 'ui.bootstrap', 'ui.router'])
app.config(function($stateProvider, $urlRouterProvider) {

  $stateProvider.state('root', {
    url: "/",
    template: '<div ui-view></div>'
  })
  .state('foo', {
    abstract: true,
    url: "/foo",
    controller: 'FooCtrl',
  })
  .state('foo.bar', {
    url: "/bar",
    controller: 'BarCtrl',
  })
  .state('bar', {
    url: "/bar",
    controller: 'BarCtrl',
  });
})

app.controller('FooCtrl', function($scope) {
  $scope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams){
    console.log("foo");
  });
});

app.controller('BarCtrl', function($scope) {
  $scope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams){
    console.log('bar')
  });
});
djangonaut
  • 7,233
  • 5
  • 37
  • 52
  • Ensure that `BarCtrl` is invoked when `#/foo/bar` – Alexey Oct 21 '14 at 14:41
  • @Alexei: could you explain a bit more? I was thinking all controllers in the foo.bar chain would get invoked, the docs say: 'when a state is "active"—all of its ancestor states are implicitly active as well.' – djangonaut Oct 21 '14 at 23:03
  • 1
    Could you prepare a fiddle? I just checked that locally and all works as expected. – Alexey Oct 22 '14 at 04:35

2 Answers2

3

While preparing a fiddle I came across my mistakes. I was thinking abstract views would not need a template since they cannot be accessed and assuming the template of foo's parent state would take over, which is not the case.

To achieve what I wanted I only had to add:

  template: '<ui-view />',

Like so:

.state('foo', {
  abstract: true,
  url: "/foo",
  controller: 'FooCtrl',
  template: '<ui-view />',
})

A related discussion: https://github.com/angular-ui/ui-router/issues/325

djangonaut
  • 7,233
  • 5
  • 37
  • 52
-2

You're not specifying the url of #/foo/bar is all.

You are specifying the state of foo.bar, but the state is only being accessed from the url of #/bar.

Change the following...

  .state('foo.bar', {
    url: "/bar",
    controller: 'BarCtrl',
  })

... to ...

  .state('foo.bar', {
    url: "/foo/bar",
    controller: 'BarCtrl',
  })

... and you should be good.

loliver
  • 9
  • 3
  • No, with the dot notation the parent's url will automatically appended to the child's, see http://plnkr.co/edit/u18KQc?p=preview – djangonaut Oct 22 '14 at 04:15