$ scope不会更新

时间:2015-08-21 23:11:43

标签: javascript angularjs angularjs-scope

情况如下面的代码。我想在调用函数时更改$ 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

3 个答案:

答案 0 :(得分:4)

尝试使用$q.all()

docker run -d -P --name web --link db training/webapp python app.py

不要忘记向控制器添加$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; }); 服务;

答案 1 :(得分:2)

编写代码的方式我不希望$ scope.pizzaList的值在你设置它和最后评估它之间有所改变。它只会在你调用setPizzaStatus()方法时被更改,即使这样,它只会在post到url1之后发生更改,而url2的get也会从你的服务器返回。

答案 2 :(得分:-2)

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

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