39

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/

2 Answers 2

75

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);       
} 
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, I know that, actually I try to change value after get response from Ajax, but suppose should be the same problem.
In order to answer that specific question I may need to see an real example of what you're trying to accomplish.
@HereHere - Simply saying "Not working" isn't very helpful. Is there a specific error you're seeing? It's possible that the function has changed since this was answered, but the link should still be relevant (docs.angularjs.org/api/ng/service/$timeout)
27

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);

1 Comment

+1 for mentioning $apply for ng-newbs like my self, here is a great explanation :

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.