我是angular.js的新手。 我对如何处理控制器中的异步事件感到困惑。
例如,在页面中,我有一个名为count的视图。 当我点击一个按钮时,控制器将计数增加1.但增加是异步的。 我想要的是,当count改变时,将通知视图并更改其值。 但是在下一次单击时,视图不会更改其值。
这是代码,例如:
<!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>更新:
谢谢你的所有答案。 但我问一个生成问题。 setTimeout函数怎么样是一个http请求? 我知道有$http可以做到这一点。 但是如果函数处理文件等等怎么办? 我没有,除了每个异步电话都有我的服务。 如果它不存在,我是否需要自己写一个?
I'm new to 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. And while I click on a button, the controller increase the count by 1. But the increase is asynchronous. What I want is, when count changed, the view will be notified and change its value. 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? I know there is $http could do this. 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?
最满意答案
使用$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); }; }或者,您可以告诉Angular使用Scope.$digest()手动应用您的更改Scope.$digest() (上面显示的$timeout服务将有效地为您执行此操作):
function Controller($scope) { $scope.count = 0; $scope.delayInc = function () { setTimeout(function () { $scope.count += 1; $scope.$digest(); }, 1000); }; }Use the $timeout service instead of the native 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):
function Controller($scope) { $scope.count = 0; $scope.delayInc = function () { setTimeout(function () { $scope.count += 1; $scope.$digest(); }, 1000); }; }更多推荐
发布评论