Ricky
Ricky

Reputation: 2907

Angular - Modify controller variables within $http call

I am trying to modify my controller's variables from within a call to $http (which receives data from an API). These controller variables are bound in my view with ng-model.

However, it's not working -- nothing is displaying!

angular
    .module('myApp')
    .controller('contactController', ['$scope', '$http', ContactController]);

function ContactController($scope, $http) {

    this.firstName = '';
    this.lastName = '';

    $http.get('../server/getdata').success(function(data) {
        // I would like to set the firstName and lastName variables 
        // from the above parent scope into here. Is this possible? 
        this.firstName = data.firstName;
        this.lastName = data.lastName;
    });
}

Any thoughts here??

Upvotes: 0

Views: 72

Answers (3)

Phil
Phil

Reputation: 164812

The problem is this in the $http callback is no longer your controller.

Assign the this value to a scoped variable, eg

var ctrl = this;

ctrl.firstName = '';
ctrl.lastName = '';

// keep in mind the "success" and "error" methods on the $http promise
// have been deprecated. Use the standard "then" method instead.
$http.get('../server/getdata').then(function(response) {
    ctrl.firstName = response.data.firstName;
    ctrl.lastName = response.data.lastName;
});

See https://docs.angularjs.org/api/ng/service/$http#deprecation-notice regarding the deprecated $http callback methods.

Upvotes: 1

Sarjan Desai
Sarjan Desai

Reputation: 3733

Change this to $scope in success function so your code will be like

$scope.firstName = data.firstName;
$scope.lastName = data.lastName;

this inside success function has function scope not global scope so this does not bind to controller.

Upvotes: -1

JC Ford
JC Ford

Reputation: 7066

Just need to preserve the value of this at the time the capture is created by assigning it to another variable such as self

angular
    .module('myApp')
    .controller('contactController', ['$scope', '$http', ContactController]);

function ContactController($scope, $http) {

    var self = this;

    this.firstName = '';
    this.lastName = '';

    $http.get('../server/getdata').success(function(data) {
        // I would like to set the firstName and lastName variables 
        // from the above parent scope into here. Is this possible? 
        self.firstName = data.firstName;
        self.lastName = data.lastName;
    });
}

Upvotes: 1

Related Questions