简体   繁体   English

如何在angular.js控制器中处理异步?

[英]How to handle asynchronous in angular.js controller?

I'm new to angular.js. 我是angular.js的新手。 I'm confused with how to handle asynchronous events in the controller. 我对如何处理控制器中的异步事件感到困惑。

For example, in a page, I have a view named count . 例如,在页面中,我有一个名为count的视图。 And while I click on a button, the controller increase the count by 1. But the increase is asynchronous. 当我点击一个按钮时,控制器将计数增加1.但增加是异步的。 What I want is, when count changed, the view will be notified and change its value. 我想要的是,当count改变时,将通知视图并更改其值。 But util the next click, the view will not change its value. 但是在下一次单击时,视图不会更改其值。

This is the code for example: 这是代码示例:

<!DOCTYPE html>
<html ng-app>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
  </head>

  <body>
    <div ng-controller="Controller">
      {{ count }}
      <form ng-submit="delayInc()">
        <input type="submit" value="Add" />
      </form>
    </div>

    <script>
      function Controller($scope) {
        $scope.count = 0;

        $scope.delayInc = function () {
          setTimeout(function () {
            $scope.count += 1;
          }, 1000);
        };
      }
    </script>
  </body>
</html>

Update: 更新:

Thanks for all your answers. 谢谢你的所有答案。 But I'm asking a generate question. 但我问一个生成问题。 How about the setTimeout function is a http request? setTimeout函数怎么样是一个http请求? I know there is $http could do this. 我知道有$http可以做到这一点。 But what if the function is something handle a file and so on? 但是如果函数处理文件等等怎么办? I don't except every async call have a service for me. 我没有,除了每个异步电话都有我的服务。 Do I need to write my own one if it dose not exist? 如果它不存在,我是否需要编写自己的?

Use the $timeout service instead of the native setTimeout : 使用$timeout服务而不是本机setTimeout

function Controller($scope, $timeout) {
    //                      ^---- Don't forget to inject the service
    $scope.count = 0;

    $scope.delayInc = function () {
        $timeout(function () {
            $scope.count += 1;
        }, 1000);
    };
}

Alternatively, you can tell Angular to apply your changes manually using Scope.$digest() (the $timeout service shown above will effectively do this for you): 或者,您可以告诉Angular使用Scope.$digest()手动应用您的更改Scope.$digest() (上面显示的$timeout服务将有效地为您执行此操作):

function Controller($scope) {
    $scope.count = 0;

    $scope.delayInc = function () {
        setTimeout(function () {
            $scope.count += 1;
            $scope.$digest();
        }, 1000);
    };
}

由于AngularJS $范围的性质,您需要使用$timeout服务替换setTimeout调用。

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

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