Javascript 为什么';在$http调用中获取的t数据,是否总是在其外部显示/使用?

Javascript 为什么';在$http调用中获取的t数据,是否总是在其外部显示/使用?,javascript,angularjs,http,data-binding,angularjs-digest,Javascript,Angularjs,Http,Data Binding,Angularjs Digest,有时,我非常随机地无法使用$http调用中接收到的数据。这样接收的数据将绑定到接收数据的变量,但不会传输到另一个变量。例如,下面的{{avariable}}显示在HTML页面中(它停止为null并显示来自服务器的数据),但{{anumber}}不会从0更改为新数据(即使我执行$scope.anumber=$scope.avariable)。有时,这个问题可以通过在$http调用本身中分配相等值来解决,而不是稍后,但这次也没有这样做。我想这和消化有关,对吗?我不一定能很好地理解它们,也不一定能理解

有时,我非常随机地无法使用$http调用中接收到的数据。这样接收的数据将绑定到接收数据的变量,但不会传输到另一个变量。例如,下面的{{avariable}}显示在HTML页面中(它停止为null并显示来自服务器的数据),但{{anumber}}不会从0更改为新数据(即使我执行$scope.anumber=$scope.avariable)。有时,这个问题可以通过在$http调用本身中分配相等值来解决,而不是稍后,但这次也没有这样做。我想这和消化有关,对吗?我不一定能很好地理解它们,也不一定能理解它们在这种情况下是如何工作的。不过,必要时我会使用$timeout

一切都在Rails/后端工作-我通过直接进入浏览器中的URL进行检查。当然,正如前面提到的,{{avariable}}确实会从null更改为服务器数据

AngularJS代码:

myangularmodule.controller('appcontroller', function($rootScope, $scope, $filter, $location, $state, $timeout, $http) {

$scope.avariable = null;

$scope.anumber = 0;


$scope.ihappenwhenthatbuttonispressed {

$timeout(function(){
 $http.get('/employees/getthisdata/' + value + '.json').success(function (data) {

        $scope.avariable = data.avariable;

    });
}, 5);

         $scope.anumber = $scope.avariable;



};


});
我的HTML页面:

<html>
<head>
 <%= stylesheet_link_tag "application" %>
 <%= javascript_include_tag "application" %>
</head>

 <body ng-app="myangularmodule">
  <div ng-controller="appcontroller">

    <button ng-click="ihappenwhenthatbuttonispressed(anumber)">
         Click me
   </button>

     {{avariable}}
     {{anumber}}

 </div>
 </body>
</html>

点击我
{{avariable}}
{{anumber}}

这是因为Javascript中的AJAX调用是异步的。您正在调用http请求,然后立即设置
$scope.anumber=$scope.avariable
,而不等待http响应。因此,当您第一次单击按钮时,实际上是在设置
$scope.anumber=null
。收到http响应时,
$scope.avariable
被设置为您的
数据.variable
,然后函数退出

如果要同时更新这两个,则需要以下内容:

$http.get('/employees/getthisdata/' + value + '.json').success(function (data) {
    $scope.avariable = data.avariable;
    updateANumber();
});
function updateANumber(){
    $scope.anumber = $scope.avariable;
}

您也可以这样做:

$http.get('/employees/getthisdata/' + value + '.json').success(function (data) {
    $scope.avariable = data.avariable;
    $scope.anumber = $scope.avariable;
});

不需要超时部分。

您发布的内容不是有效的Javascript。另外,当使用
$http
$http.get
时,不需要
$timeout
,因为它是异步的,因此success函数可能会在$http.get块结尾后的代码行之后运行(很长时间之后)。这是因为Javascript不是完全异步的。AJAX(通常)是,在setTimeOut和setInterval等地方调用的函数也是。。。但是说“javascript是异步的”并不十分准确