Doug S. Doug S. - 1 month ago 9
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

and angular. I have wrapped the gApi call into a directive. The directive takes a string
and a function called
. 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 (
is assigned in the constructor) function, complaining that
is undefined.

What can I do to fix this?


class LoginController {
constructor($scope, $log) { = '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());


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


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

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


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

let onSuccessFunction = LoginCtrl.loggedIn;

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.