admin管理员组

文章数量:1287935

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.

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.

Share Improve this question asked Jul 24, 2015 at 22:31 user3043893user3043893 3114 silver badges13 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 8

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 piler: 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./2014/03/traceur-is-awesome-but-still-little.html

The simplest way is to put your this inside an object.

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

  $scope.$on('changeTitle', function (event, data) {
    self.title = data;     // Due to scope inheritance in javascript, self is defined here.   
  });

});

This version is also best practice for many of angular users, including John Papa (he calls it vm instead of self).

https://github./johnpapa/angular-styleguide#style-y032

And you can use the

Angular.bind(this, function(){})

as described here and in this answer

so you will have something like:

this.defaultCity = 'myvalue';
callHttpService(this.defaultCity).then(angular.bind(this, function(res) {
    this.defaultCity = res.data;
}));

本文标签: javascriptAngularJS using bind(this)Stack Overflow