0

Regarding $scope and this when using ui-router,

If I am using the controllerAs syntax, ie:

.config(['$stateProvider', function($stateProvider) {
    $stateProvider
        .state('app.login', {
            url: '/login',                  
            templateUrl: 'modules/login/login.html',
            controllerAs: 'login',
            controller: 'LoginCtrl',
            data: {
                authorizedRoles: [USER_ROLES.all]
            }
        });
}])

In my controller then, I'm using this instead of $scope. So I have code like this in my login controller:

this.func1 = func1;
this.func2 = func2;
this.message = "Hello world!";

But I'm also using $scope to listen to globally broadcasted events from my $rootScope, because if I remember correctly, this doesn't have methods belonging to $scope, even though they are being interchanged.

$scope.$on('event', handler);

So I'm listening to an event broadcast by $rootScope and calling some other controller logic, like func2, when this event is broadcasted:

$scope.$on('auth-login-failed', function(event) {
// call some other function in controller
});

What if I wanted to call func2 inside the $on handler? Should I do some convention where I initialize something like this in my controller?

var that = this;

$scope.$on('auth-login-failed', function(event) {
    this.func2();
});

I'm just curious on the best way to proceed and what the general convention is here. Is it proper to use both $scope and this, and what are the main differences between the two, since they can be interchanged?

Radim Köhler
  • 122,561
  • 47
  • 239
  • 335
Thomas
  • 323
  • 1
  • 3
  • 14
  • there are multiple articles that describe the differences in detail here already.... essentially, $scope *always* exists, and using ControllerAs creates the controller as a property on $scope. As for referring to the controller inside callbacks, using an alias or using `.bind()` are both viable, and are more of an issue with JavaScript closures than with angular itself. ***technically***, you could refer to `$scope.login.func2()`. – Claies Oct 25 '15 at 15:06

1 Answers1

0

Your suggestion, too keep the logical context in some variable - is really good, and good practice:

var _this = this;

$scope.$on('auth-login-failed', function(event) {
    _this.func2();
});

In fact, that is the way how Typescript is doing the same, behind the scene for us. It is called

Arrow function

and will look like this in typescript:

$scope.$on('auth-login-failed', (event) => {
    this.func2();
});

becuase Typescript compiler behind the scene will do the above trick with logical scope being kept in some variable.

I would suggest to you:

... do the best to start to use Typescript. It is the future of the angular worlds anyway...

There are some links to some details how to create angular's controller in Typescript, including working examples

Community
  • 1
  • 1
Radim Köhler
  • 122,561
  • 47
  • 239
  • 335