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?
.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 2 days ago