如何访问更新的$ scope范围值?

时间:2018-06-01 12:28:16

标签: angularjs angularjs-scope

$scope.widgettype = ' ';
$scope.getwidgettype().then(function (data) {
                    $scope.widgettype = data;
                    $scope.showdimaxis = data === 'bubble';
                });
                console.log($scope.widgettype);

作为angularjs的新手,我只是被困在这里。 Console.log返回空白值(不是更新的值)。

如何在其他一些函数中访问$ scope.widgettype(更新值)的值?有没有其他方法可以达到这个目的?

你的帮助真的很感激!

2 个答案:

答案 0 :(得分:1)

angularjs上的代码是异步的。所以

$scope.getwidgettype().then(function (data) {
                $scope.widgettype = data;
                $scope.showdimaxis = data === 'bubble';
            });

需要几毫秒才能完成。 尝试在then子句中转换console.log

$scope.widgettype = ' ';
$scope.getwidgettype().then(function (data) {
     $scope.widgettype = data;
     $scope.showdimaxis = data === 'bubble';
     console.log($scope.widgettype);
});

答案 1 :(得分:1)

要在当前功能之外使用widgettype,您需要返回承诺$http已经做过)并解决它你需要检索价值的时间。

例如:

$scope.widgettype = ' ';
var promise = $scope.getwidgettype().then(function (data) {
    $scope.widgettype = data.data; // `.then` wraps it in an object, so you need `.data`
    $scope.showdimaxis = data.data === 'bubble';
    return data.data; // return the value within a Promise
});

并在其他地方使用:

promise.then(function(data){ // resolving it every time we need `data`
    console.log(data); // we returned `data.data`, so this time `.data` is not needed
})

最好为此编写服务/工厂,这可能会像这样返回:

return this.getwidgettype().then(function(response) { // return a promise
    return response.data; // and return your data
});