0

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!

3
  • You cannot call service method using this, you need to call it using <service-name>.<method-name> Commented Feb 22, 2016 at 7:20
  • I think var vm = this; is a perfect solution in this situation. Why do you want alternative to that? Does this not satisfy any of your scenarios? Commented Feb 22, 2016 at 7:23
  • I want to remove usage of var declarations for security improvement Commented Feb 22, 2016 at 8:46

1 Answer 1

1

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));
  });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.