Sam Jeston Sam Jeston - 6 months ago 87
AngularJS Question

Handling events in ES6 Angular controllers

I'm experimenting with ES6 classes for my controllers.

Previously if I was listening to a rootScope event with ui-router, I could do something like this:

$rootScope.$on('stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
console.log(toState)
}


and toState would easily be accessible.

My ES6 controller currently looks like this:



class NavbarController {
constructor ($rootScope) {
this.name = 'navbar'
this.$rootScope = $rootScope

this.$rootScope.$on('stateChangeStart', this.activeNav())
}

activeNav () {
console.log('This is called')
return (event, toState, toParams) => {
console.log('This is never called')
}
}
}

NavbarController.$inject = ['$rootScope']
export default NavbarController





From posts I had read I thought I was on the right track however the function I am returning is not called, and I can't figure out how to access the event parameters.

So what is the correct way to handle events in ES6 angular controllers?

Answer
activeNav () {
  console.log('This is called')
  return (event, toState, toParams) => {
    console.log('This is never called')
  }
}

You were using incorrect syntax here. Arrow functions need to have "=>" arrow hence their name. You have some more syntax errors in your code. Consider using some IDE or other way of automated syntax checking.

Also name of event is $stateChangeStart not stateChangeStart.

Comments