Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update Angular model with $http response?

I'm building an http request in Angular using $http and trying to update a model located in '$scope' with the data return in the response. When I receive the response from my node backend, I'm setting '$scope.data = data;' within the success callback. When I step through the javascript, I can see that the response is correct and the status code is present. Here's a sample of what I'm trying to do:

angular.module("Sample").controller('MainCtrl', ['$http', '$scope', function($http, $scope) {

this.testcall = function (url) {

  $http.post(url).success(function (data, status) {
    console.log(data);
    $scope.data = data;
    $scope.status = status;
    console.log($scope.data);
  }).error(function (data, status) {
    console.log('failed');
    $scope.response = 'failed call';
    $scope.status = status;
  });
};
}

And in my html template I have the controller set in the div and I'm trying to display that response.

<div ng-controller="MainCtrl as main">
  {{data}}
</div>

I can set a value to data and have it appear on load, but when the value changes it's not being redrawn. It was my understanding that '$http' causes '$digest' to be called which should redrawn any modified models.

like image 320
Kyle Avatar asked Apr 16 '15 13:04

Kyle


People also ask

How do you wait till the response comes from the $HTTP request in angular?

Solution. The solution of this problem is to use the promise returned by $http services in AngularJS and use . then function. This ensures that the first function response is received and then only code inside .

What is $HTTP service in AngularJS?

The $http service is a core AngularJS service that facilitates communication with the remote HTTP servers via the browser's XMLHttpRequest object or via JSONP. For unit testing applications that use $http service, see $httpBackend mock. For a higher level of abstraction, please check out the $resource service.


1 Answers

To get it working you need to bind scope variable to controller this context write this.data = data; instead of $scope.data because you are using controllerAs syntax.

Code

  $http.post(url).success(function (data, status) {
    console.log(data);
    this.data = data;
    this.status = status;
    console.log(this.data);
  }).error(function (data, status) {
    console.log('failed');
    this.response = 'failed call';
    this.status = status;
  });

Markup

<div ng-controller="MainCtrl as main">
  {{main.data}}
</div>
like image 163
Pankaj Parkar Avatar answered Sep 19 '22 08:09

Pankaj Parkar