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.

1 Answer 1

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.

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

2 Comments

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?
Please, read this 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)

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.