How to bind to "this" in Angular 1.4 new router Components, instead of using local vars?

95 views Asked by At

I have a components controller and in order to use this inside local functions I have to declare a local var.

Is there a better way to bind to "this" inside new angular router? For example this function:

function appController ($router, $scope, $location,  authService, $scope, $timeout) {
  this.authService = authService;
  this.pageTitle = "title";
  _this = this;
  //when location changes does some stuff
  $scope.$on('$locationChangeSuccess', function (event, newLoc, oldLoc){
    //hides the notifier
    _this.accountCollapse = false;
    _this.pageTitle = $location.path();
  });
}

Is there another way to do it? Faster/better?

1

There are 1 answers

1
Mikalai On

I think this way is the fastest. But you must declare variable _this with operator var to prevent some errors in the future

var _this = this;

Another option will be to bind this to listener like that:

  $scope.$on('$locationChangeSuccess', (function (event, newLoc, oldLoc){
    //hides the notifier
    this.accountCollapse = false;
    this.pageTitle = $location.path();
  }).bind(this));