5

New to AngularJSs. Wondering why setTimeout is not working. Is it true that it doe snot work with AngularJS?

jsfiddle.net

<div ng-controller="MyCtrl">
    <select ng-model='form'  ng-options='option.value as option.name for option in typeOptions'></select>
</div>
<script>
var myApp = angular.module('myApp',[]);


function MyCtrl($scope) {

    //$scope.typeOptions = [];
    alert("hi23");
    $timeout(function() {
        alert("hi");
        $scope.typeOptions =
    [
    { name: 'Feature', value: 'feature' }, 
    { name: 'Bug', value: 'bug' }, 
    { name: 'Enhancement', value: 'enhancement' }
    ]; 
     $scope.form =  $scope.typeOptions[1].value;                     
    }, 3000);


}
</script>

Thanks.

2 Answers 2

8

you need to inject $timeout. Observe the following change

function MyCtrl($scope, $timeout) { 
    ....
}

See the $timeout docs for more information


Furthermore, this style of declaring controllers is not recommended. I would encourage re-fractoring to the following...

myApp.controller('MyCtrl', ['$scope', '$timeout', function($scope, $timeout) {
    .... 
}]);
Sign up to request clarification or add additional context in comments.

3 Comments

In addition to what sal niro said, you need to initiate your controller. angular.module('myApp').controller('MyCtrl', MyCtrl);
Thanks guys! Here is the link to a working version with the style you recommended: jsfiddle.net/m4ozztsk
Here's a good article on use of $timeout and $interval tutorials.jenkov.com/angularjs/timeout-interval.html
4

Angular has a list of watchers, which is all the variables and objects that bind the view with its model. Angular keeps listening for events that change any of these and starts a digest cycle to update the DOM with the new values.

When you use setTimeout, it runs asynchronously and all the code inside setTimeout is not watched by Angular, even though it might be changing one of the Angular scope values.

So you can either use $timeout as suggested above or you can wrap your setTimeout code within $scope.$apply, which tells Angular to watch for it also.

This is also a good practice for any external Jquery libraries you may be using within your Angular app. Although recommended way is to use Angular wrappers for such libraries.

Comments

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.