Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS using bind(this)

I have lately switched to using "this" in the controllers and controllerAs in ngRoute and Directives, rather than $scope directly. Although I really enjoy the way the code looks, I have to bind "this" to each function - manually.

Example:

app.controller('mainController', function ($scope, Restangular) {
    this.title = '';

    $scope.$on('changeTitle', function (event, data) {
        this.title = data;
    }.bind(this)); //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

});

I understand why I have to do that ("this" context constantly changes), is there any better solution (cleaner, usable) I should consider doing?

Thanks.

like image 640
user3043893 Avatar asked Feb 24 '26 05:02

user3043893


1 Answers

Fat arrow functions in ES6 are specifically added to solve this problem. With a fat arrow function you inherit the context of the parent scope, so you no longer have to use bind or var that = this. So you could look into transpiring.

app.controller('mainController', function ($scope, Restangular) {
  this.title = '';

  $scope.$on('changeTitle', (event, data) => {
    this.title = data;
  });
});

Angular 2 is written in ES6 and uses the Traceur compiler: http://angularjs.blogspot.sg/2014/03/angular-20.html and here's a short post on how you can use it with your own code: http://www.benlesh.com/2014/03/traceur-is-awesome-but-still-little.html

like image 113
Kit Sunde Avatar answered Feb 25 '26 17:02

Kit Sunde



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!