2

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?

Community
  • 1
  • 1
whistling_marmot
  • 3,561
  • 3
  • 25
  • 39
  • Please,Let me know is it working or not? – RIYAJ KHAN Feb 03 '16 at 12:32
  • @JMK The second code block (without the fat arrow) is ES5 syntax – whistling_marmot Feb 03 '16 at 12:45
  • Not fat, just arrow. And it's not a _"syntax for anonymous functions". An arrow function is a special type of function. `controller` expects a constructor function, which can never be an arrow function. – a better oliver Feb 03 '16 at 13:50
  • Possible duplicate of [Arrow function vs function declaration / expressions: Are they equivalent / exchangeable?](http://stackoverflow.com/questions/34361379/arrow-function-vs-function-declaration-expressions-are-they-equivalent-exch) – Felix Kling Feb 03 '16 at 14:32

2 Answers2

1

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.

Yoann Prot
  • 514
  • 2
  • 8
0

Angular calls the controller function like this: fn.apply(self, args); where self (which becomes this in the invoked function) is an object that has the required fields - i.e. myVariable in the example.

Arrow functions ignore the first of apply's arguments. So as @Yoann says, we must use function() {...} rather than () => {...}.

whistling_marmot
  • 3,561
  • 3
  • 25
  • 39