简体   繁体   中英

How to change value after delay by using angularjs?

I created basic application based on angularjs

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:

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. Really strange. Did I miss something?

Actually I try to change value after get response from Ajax, but suppose should be the same problem.

Thanks,

Here is my example: http://jsfiddle.net/6uKAT/20/

Try using: $timeout

Angular's wrapper for window.setTimeout. The fn function is wrapped into a try/catch block and delegates any exceptions to $exceptionHandler service.

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

Updated Fiddle

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(function() {
    $scope.val = true;
}, 3000); 

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

For timeout use $timeout and it will call $scope.$apply() for you.
Likewise, for ajax use $http .

if you can't use these, then you must call $scope.$apply() yourself:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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