penguinsource
penguinsource

Reputation: 1190

Angularjs http call and saving received data to the controller instance

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 !

Upvotes: 0

Views: 46

Answers (2)

GregL
GregL

Reputation: 38113

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
        });
});

Upvotes: 2

Michael Kang
Michael Kang

Reputation: 52847

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

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

Upvotes: -1

Related Questions