0

I am creating an simple TODO app using AngularJS, i POST the data to server when response comes, that response i want to store it existing variable and refresh the view. i.e

// This stores on page load, its working fine

var todos = $scope.todos = sever_passed_data;

but when i do,

$scope.$watch('todos', function () {
    var request = $http({
        method: "post",
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        url: my_url,
        data: $.param({todos_list: angular.toJson(todos)})
    });
    request.success(function(responce){
        var todos = $scope.todos = responce;
    });
}, true);

after this it gives me weird(it goes in infinite loop and posting data to server) output, i mean the responce doesn't stores in todos variable.

Jay
  • 3,353
  • 5
  • 25
  • 34
  • It looks as if you're watching `todos` on your scope, then updating it in the response, which causes another watch cycle, which updates it again, which causes another watch cycle, and on and on... – Marc Kline May 16 '14 at 04:25
  • @MarcKline yeah i think this is what its happening, suggest me how to solve this? – Jay May 16 '14 at 04:45
  • First suggestion would be to place your $http/model stuff in services. That can help to keep you out of trouble. Then look at alternatives to using $watch. For instance, you could update the view as soon as the user submits, then manually trigger a POST and only rollback the UI update if there's a failure returned from the server. – Marc Kline May 16 '14 at 05:19

1 Answers1

0

If you want to store the returned value of the HTTP POST in the $scope.todos variable, you should use response.data. response contains the entire HTTP response, including the response code, response headers, response body, etc.

Why are you declaring the local variable todos? It will go out of scope as soon as the function exits. just assign $scope.todos. Also, you might want to use then instead of success. Here's an example:

$http({
    method: "POST",
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    url: my_url,
    data: $.param({todos_list: angular.toJson(todos)})
}).then(function(response) {
    $scope.todos = response.data;
});
metacubed
  • 7,031
  • 6
  • 36
  • 65