更新美元范围.POST后的变量值



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

// 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变量

如果您希望将HTTP POST的返回值存储在$scope.todos变量中,则应使用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;
});

最新更新