Sam Jeston
Sam Jeston

Reputation: 71

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?

Upvotes: 1

Views: 1503

Answers (2)

Sam Jeston
Sam Jeston

Reputation: 71

Sielakos pointed me to my problem, foolishly using the wrong event. The working snippet is below in case it helps others.

class NavbarController {
  constructor ($rootScope) {
    this.$rootScope = $rootScope
    this.$rootScope.$on('$stateChangeStart', this.activeNav())
  }

  activeNav () {
    return (event, toState, toParams) => {
      console.log(toState.name, toParams)
    }
  }
}

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

Upvotes: 1

sielakos
sielakos

Reputation: 2404

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.

Upvotes: 1

Related Questions