There is a problem I have always run into and its resulting into inconsistency with the definition of controller scope variables.
As you might be aware that using controllerAs syntax you have to attach all the variables with this instance inside the controller function as shown below:
angular.module('angularJsInternationalizationApp')
.controller('MainCtrl', function (SampleService) {
this.awesomeThings = [
'HTML5 Boilerplate',
'AngularJS',
'Karma'
];
this.translatedFromService = '';
SampleService.getTranslation().then(function(data){
this.translatedFromService = data;
});
});
Now the problem is this.translatefDromService cannot be updated from the success or error functions of any service or as a matter of fact any other function because it takes this as an instance of the new function and not the controller.
What can be done in such scenarios.
I have used one solution where your tag this to vm. var vm = this at the beginning of the controller but apart from this is there any solution?
Cheers!
You have 2 options:
1) Use the
vm = this
approach, keeping a link tothis
context of the controller:2) Use the
bind()
method on the handler, which will modify the context of the invoked function to controller'sthis
: