简体   繁体   English

如何使用angularjs在延迟后改变值?

[英]How to change value after delay by using angularjs?

I created basic application based on angularjs 我创建了基于angularjs基本应用程序

HTML: HTML:

<div ng-app="miniapp">
<div ng-controller="Ctrl">
    My name is 
    <input type="text"/>   
    Val: {{val}}
    <br/>
    <button ng-disabled="val">Submit</button>        
</div>    

JS: JS:

var app = angular.module('miniapp', []);

var glob;
function Ctrl($scope) {      
    glob = $scope;    
     $scope.val = false;

     window.setTimeout(function() {
            $scope.val = true;
        }, 3000);             
}

 window.setTimeout(function() {
            glob.val = true;
        }, 3000); 

As you can see I try to change val to true after 3 sec by 2 ways but no one is working for me. 正如你所看到的那样,我尝试在3秒后用2种方式将val改为true ,但没有人为我工作。 Really strange. 真奇怪。 Did I miss something? 我错过了什么?

Actually I try to change value after get response from Ajax, but suppose should be the same problem. 实际上我在尝试从Ajax获得响应后尝试更改值,但是假设应该是同样的问题。

Thanks, 谢谢,

Here is my example: http://jsfiddle.net/6uKAT/20/ 这是我的例子: http//jsfiddle.net/6uKAT/20/

Try using: $timeout 尝试使用: $timeout

Angular's wrapper for window.setTimeout. Angular的window.setTimeout包装器。 The fn function is wrapped into a try/catch block and delegates any exceptions to $exceptionHandler service. fn函数被包装到try / catch块中,并将任何异常委托给$ exceptionHandler服务。

$timeout(fn[, delay][, invokeApply]);

Updated Fiddle 更新小提琴

JavaScript JavaScript的

var app = angular.module('miniapp', []);

function Ctrl($scope, $timeout) {  
     $scope.val = false;
     $timeout(function(){$scope.val = true}, 3000);       
} 

You are making changes to scope outside of what angular knows about (inside a timeout). 您正在更改范围之外的范围(在超时内)。
So you should use $timeout .. otherwise you have to use $scope.$apply() 所以你应该使用$timeout ..否则你必须使用$scope.$apply()

$timeout(function() {
    $scope.val = true;
}, 3000); 

http://jsfiddle.net/6uKAT/21/ http://jsfiddle.net/6uKAT/21/

For timeout use $timeout and it will call $scope.$apply() for you. 对于超时使用$timeout ,它将为您调用$scope.$apply()
Likewise, for ajax use $http . 同样,对于ajax使用$http

if you can't use these, then you must call $scope.$apply() yourself: 如果你不能使用这些,那么你必须调用$scope.$apply()你自己:

 window.setTimeout(function() {
     $scope.$apply(function() {
        $scope.val = true;
     });
 }, 3000);

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

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