Search code examples
angularjsecmascript-6lexical-scope

Passing scope variables to an AngularJS controller using fat arrows


I'm updating an AngularJS application to use fat arrow syntax for anonymous functions. I know that I need to use version 1.5, but some things still don't work. For example, here I have a custom directive that passes the string 'hello' to its controller, which then outputs the string as an alert:

<div data-my-directive="hello">Text that will be replaced by my-template</div>

angular
    .module('myModule')
    .directive('myDirective', () => (
            {
                restrict: 'A',
                templateUrl: 'my-template',
                controller: 'myController',
                controllerAs: 'myCtrl',
                bindToController: true,
                scope: {myVariable : '@myDirective'}
            }))
    .controller('myController', () => {
        alert('the scope variable is: ' + this.myVariable );
    }

But this alerts 'the scope variable is: undefined'.

If I change the controller definition to use ES5 syntax, then it alerts 'the scope variable is: hello', as expected.

    .controller('myController', function() {
        alert('the scope variable is: ' + this.myVariable);
    }

I guess that this is something to do with the binding of this.

Is there a way to use the fat arrow notation when passing scope variables as above?


Solution

  • In this case, you have to use function instead of ()=>.

    If you do :

    .controller('myController', () => {
        console.log(this); // -> window
    })
    

    If you use arrow function here, this === window. A controller need a real scope to work properly. I am pretty sure you doesn't want window as common object for all controllers in your app :)

    Arrow function is really useful with class and callback but should not be use every time.