i'm creating angular app using es6 features, i'm using babel transpile js. decided not use es6 modules, instead of regular es2015
preset i'm using es2015-script
.
the problem way babel compiles arrow functions. i'm using angular's controlleras notation, this
angular.module('appcontrollers') .controller('storycontroller', ['storyprovider', (storyprovider)=>{ this.plaintext='test plain'; }]);
this code transpiled
var _this = this; angular.module('mycontrollers') .controller('storycontroller', ['storyprovider', function (storyprovider) { _this.plaintext = 'test plain'; }]);
so this
in wrong scope , binding not working. when manually changed compiled code
angular.module('mycontrollers') .controller('storycontroller', ['storyprovider', function (storyprovider) { var _this = this; _this.plaintext = 'test plain'; }]);
it works fine.
why babel setting intermediate _this
variable way? there babel preset handle properly? should go es6 modules? had same problem described in issue angular 1.5 component , babel in first place, that's why used es2015-script
preset.
ok there several approaches here
1) use es6 class
class storycontroller{ constructor(storyprovider){ this.plaintext='test plain'; this.storyprovider=storyprovider; } }
this adds 1k of helper functions, plus can see, need save injected dependencies in constructor.
2) rid of arrow function in main controller definition , use in methods. like
function storycontroller(storyprovider){ this.plaintext='test plain'; this.asynctest=()=>{ settimeout(()=>{ console.log(this.plaintext); }, 100); }; }
this transpiles nice
function storycontroller(storyprovider) { var _this = this; this.plaintext = 'test plain'; this.asynctest = function () { settimeout(function () { console.log(_this.plaintext); }, 100); }; }
which scopes _this
variable.
Comments
Post a Comment