codingFun codingFun - 5 months ago 35
AngularJS Question

setTimeout() not working in angularjs?

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.

Answer

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) {
    .... 
}]);
Comments