繁体   English   中英

$ scope没有更新

[英]$scope doesn't get updated

情况类似于下面的代码。 我想在调用函数时更改$ scope.pizzaList和$ scope.selectedPizza的值,但似乎没有改变。 我想这与$ scope的深度有关,但我不明白。 如何使这些值得到更新? 提前致谢!

$scope.pizzaList = "some initial value";
$scope.selectedPizza = "some initial value";

$scope.setPizzaStatus = function (setStatus) {

    $http.post('url1', { userID: $scope.pizzaioloID, pizzaID: $scope.selectedPizzaID, statusNum: setStatus }).
    then(function(response) {

        $http.get("url2")
        .success(function (response) {
            $scope.pizzaList = response;
        });

        $http.get("url3")
        .success(function (response) {
            $scope.selectedPizza = response[0];
        }); 

    }, function(response) {

        console.log("Error");
    });
}   

$scope.pizzaList // doesn't get updated 
$scope.selectedPizza // doesn't get updated

尝试使用$ q.all()

$q.all([
    $http.get("url2"),
    $http.get("url3")
]).then(function(values){
    $scope.pizzaList = values[0];
    $scope.selectedPizza = values[1];//or values[1][0], It depends on data format;
}, function(error){
    //error processing;
});

不要忘记为控制器添加$q服务。

我的代码编写方式我不希望$ scope.pizzaList的值在设置它和最后评估它之间发生变化。 仅当您调用setPizzaStatus()方法时,它才会更改,即使如此,它也只会在服务器上返回到url1的帖子和从url2获取的get之后才更改。

当您发出Get请求时,您的Javascript代码将输入“另一个任务”。 因此,有时当前范围未按预期更新。 尝试通过调用“ Apply”来更新作用域,如下所示:

$http.get("url2")
.success(function (response) {
    $scope.pizzaList = response;
    $scope.$apply(); //or $scope.$applyAsync();
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM