Doug S. Doug S. - 3 months ago 20
AngularJS Question

ES6 Angularjs directive, passed in function from calling controller has no constructor variables

I am using ES6 but I am not sure this is an ES6 issue

I am trying to implement a 'login with google' button using the google api

gApi
and angular. I have wrapped the gApi call into a directive. The directive takes a string
clientId
and a function called
onSuccessFunction
. The on success function gets called on a successful sign in. Currently I am just trying to log the profile information on successful login, but I get an error when it tries to call the first this.log.debug (
this.log
is assigned in the constructor) function, complaining that
this
is undefined.

What can I do to fix this?

Controller

class LoginController {
/*@ngInject*/
constructor($scope, $log) {
this.name = 'login';
this.clientId = 'ourClientID';
this.log = $log;
}

loggedIn(googleUser) {
let profile = googleUser.getBasicProfile();
this.log.debug('ID: ' + profile.getId());
this.log.debug('Name: ' + profile.getName());
this.log.debug('Image URL: ' + profile.getImageUrl());
this.log.debug('Email: ' + profile.getEmail());
}
}


View

<google-login-button client-id="loginCtrl.clientId" on-success-function="loginCtrl.loggedIn"></google-login-button>


Directive

class googleLoginButton {
/*@ngInject*/
constructor() {
this.template = '<div></div>';
this.scope = {
clientId: '@',
onSuccessFunction: '&'
};
}

link(scope, element, attrs) {
var div = element.find('div')[0];
div.id = attrs.clientId;
gapi.signin2.render(div.id, { 'onsuccess': scope.onSuccessFunction() }); //render a google button, first argument is an id, second options
}
}

Answer

When a method is being passed through binding, it loses its context. It is the same thing as doing

let onSuccessFunction = LoginCtrl.loggedIn;
onSuccessFunction(...);

It should be

  constructor($scope, $log) {
    ...
    this.loggedIn = this.loggedIn.bind(this);
  }

As a rule of thumb, every method that is supposed to be used as a callback, should be bound.

Comments