POST后更新$ scope.variable值

时间:2014-05-16 04:03:55

标签: angularjs

我正在使用AngularJS创建一个简单的TODO应用程序,我在响应到来时将数据发送到服务器,该响应我想存储它现有的变量并刷新视图。即

// This stores on page load, its working fine

var todos = $scope.todos = sever_passed_data;

但是当我这样做时,

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

之后它让我很奇怪(它进入无限循环并将​​数据发布到服务器)输出,我的意思是responce没有存储在todos中变量

1 个答案:

答案 0 :(得分:0)

如果要在$scope.todos变量中存储HTTP POST的返回值,则应使用response.dataresponse包含整个HTTP响应,包括响应代码,响应标头,响应正文等。

为什么要声明局部变量todos?一旦函数退出,它将超出范围。只需指定$scope.todos即可。此外,您可能希望使用then而不是success。这是一个例子:

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