Angular JS using controllerAs and this syntax with scope or this variables

121 views Asked by At

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!

1

There are 1 answers

0
Dmitri Pavlutin On BEST ANSWER

You have 2 options:

1) Use the vm = this approach, keeping a link to this context of the controller:

angular.module('angularJsInternationalizationApp')
  .controller('MainCtrl', function (SampleService) {
    var vm = this;
    vm.awesomeThings = [
      'HTML5 Boilerplate',
      'AngularJS',
      'Karma'
    ];

    vm.translatedFromService = '';
    SampleService.getTranslation().then(function(data){
        vm.translatedFromService = data;
    });
  });

2) Use the bind() method on the handler, which will modify the context of the invoked function to controller's this:

angular.module('angularJsInternationalizationApp')
  .controller('MainCtrl', function (SampleService) {
    this.awesomeThings = [
      'HTML5 Boilerplate',
      'AngularJS',
      'Karma'
    ];

    this.translatedFromService = '';
    SampleService.getTranslation().then(function(data){
        this.translatedFromService = data;
    }.bind(this));
  });