如何在angularjs中访问方法之外的Scope值

时间:2017-07-04 13:34:06

标签: angularjs

在下面的AngularJS控制器中:

  1. 最初我宣布了2个全局变量,xy
  2. 然后我使用$http.get()执行AJAX调用,我从后端获得了正确的响应,并在变量xy中保留了所需的响应值。
  3. alert消息中,我正在尝试打印xy的值。
  4. 我在Stack Overflow中经历了其他问题和答案,这是一个重复的问题,但在这里并不成功。

    app.controller('MyController', function($scope, $http, $rootScope) {
        $scope.x = '';
        $scope.y = '';
        $http.get('javaAngularJS').then(function (response) {
            var data = response.data;
            $scope.smsresult = data;
            //need to print following x and y values in below alert message
            $scope.x = $scope.smsresult.failure;
            $scope.y = $scope.smsresult.success;
        });
    
        alert(x+"   "+y);
    });
    

    但在警告消息中,x*y的值未打印。上面的代码中我的错误是什么?

3 个答案:

答案 0 :(得分:2)

尝试在响应函数中设置'x'和'y',如

$http.get('javaAngularJS').then(function (response)
{
  var data = response.data;
  $scope.smsresult = data;
  //need to print following x and y values in below alert message
  $scope.x = $scope.smsresult.failure;
  $scope.y = $scope.smsresult.success;
 alert($scope.x+"   "+$scope.y);
 });

Ajax调用是异步的,因此当您打印警报时,ajax尚未完成。

如果你想在成功块之外有处理逻辑,你可以将它放在单独的函数中并在成功部分调用它:

$http.get('javaAngularJS').then(function (response)
{
  $scope.processSmsResponse(response);
});

$scope.processSmsResponse = function (response){
//your logic here
}

答案 1 :(得分:0)

你不应该使用$ scope.x / y吗?现在它们是未定义的变量x和y。

x = $scope.smsresult.failure; y = $scope.smsresult.success;

$scope.x = $scope.smsresult.failure; $scope.y = $scope.smsresult.success;

(我会评论,但没有业力)

答案 2 :(得分:-1)

app.controller('MyController', function($scope, $http, $rootScope)
{
$scope.x = '';
$scope.y = '';
$http.get('javaAngularJS')
.then(function (response)
{
    var data = response.data;
    $scope.smsresult = data;
    //need to print following x and y values in below alert message
    $scope.x = $scope.smsresult.failure;
    $scope.y = $scope.smsresult.success;
});
alert($scope.x+"   "+$scope.y);
});