0
app.controller('sampleCtrl', function($scope, $http, nonService){
    this.someVar = 'Hello World';

    $http.post('funcsPHP/2.0/getConditionProductService.php', 
        { 'product' : angular.toJson(this.productObj) }).
        success(function(data, status, headers, config) {
            $scope.saveData = data; // works fine
            this.saveData = data // 'this' doesnt refer to the controller 'sampleCtrl' anymore, but to the $http instance, right ?
        }).
        error(function(data, status, headers, config) {
            console.log("ERROR");
            // log error
    });
});

I am aware that I am able to save data to the $scope, but I would like to know how I would be able to save data to a controller variable, such as 'this.someVar'. Do I have to inject an instance of my controller into the $http ?

Cheers !

2 Answers 2

2

There are a few ways.

The easiest is to just assign a variable to point to the this value in your controller. The most common names are _this, self, and that.

So you get:

app.controller('sampleCtrl', function($scope, $http, nonService){
    this.someVar = 'Hello World';
    var self = this;

    $http.post('funcsPHP/2.0/getConditionProductService.php', 
        { 'product' : angular.toJson(this.productObj) }).
        success(function(data, status, headers, config) {
            $scope.saveData = data;
            self.saveData = data;
        })
        .error(function(data, status, headers, config) {
            console.log("ERROR");
            // log error
        });
});

The other way is to use Function#bind() for your success handler to set this correctly inside it.

That would give you:

app.controller('sampleCtrl', function($scope, $http, nonService){
    this.someVar = 'Hello World';

    $http.post('funcsPHP/2.0/getConditionProductService.php', 
        { 'product' : angular.toJson(this.productObj) }).
        success((function(data, status, headers, config) {
            $scope.saveData = data;
            this.saveData = data;
        }).bind(this))
        .error(function(data, status, headers, config) {
            console.log("ERROR");
            // log error
        });
});
Sign up to request clarification or add additional context in comments.

Comments

-1

Use "Controller As" way of accessing your controllers instance variables:

 <div ng-controller="sampleCtrl as ctrl">
      {{ctrl.someVar}}
 </div>

1 Comment

The OP was not asking how to refer to the controller instance variable in the markup, they were asking how to add a property to the controller instance inside an async callback in the controller.

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.