1

Is there a way to bind a function to specific state name instead of the state change event?

For example, this is what I do now:

  $scope.$on('$stateChangeSuccess', function(evt, toState, toParams, fromState, fromParams) {
    console.log(toState.name);
  });

Basically, I bind to $stateChangeSuccess and get toState.name to process a specific task. But I feel this is a bit overkill as it binds to a general event. I just want to bind to a specific state such as toState.name = "foo" or something like that.

Any pointer?

Thanks.

Nathaniel Johnson
  • 4,731
  • 1
  • 42
  • 69
HP.
  • 19,226
  • 53
  • 154
  • 253

1 Answers1

1

As stated here: State Change Events

All these events are fired at the $rootScope level.

I would say, this is the advantage of this kind of eventing system. It allows us to hook on some functionality as a standard AOP framework (Regardless of the specific state beeing navigated to).

Using the if or switch with combination of multiple files/listeners... could make it clear and managable.

Side NOTE: I do prefer to has one (if possible) file for an aspect, to use suffix e.g. (ctrl.js, dirc.js, listner.js) to distinguish the kind.

Radim Köhler
  • 122,561
  • 47
  • 239
  • 335
  • So if I have 20 controllers all subscribed to `$stateChangeStart` but they require different `state.name` to act upon, isn't that a little **bloated** in the event loop somewhere (in term of performance)? Or my worry is non-sense? – HP. Jan 02 '14 at 07:34
  • Please, read this http://stackoverflow.com/a/9693933/1679310 about more details about the performance. I would hardly explain that better ;) Summary: 20 is not an issue ;) I would say, prefere better code maintainance (searching, extending) over too much performance improvements (if reasonable;). The AOP(event listeners) placed outside of the standard implementation, even with some overhead to process 20 of them, will give us lot of profit later.. once the application is mature (and large) – Radim Köhler Jan 02 '14 at 07:42