Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 742
packetie Avatar asked May 26 '15 23:05

packetie


1 Answers

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) {
    .... 
}]);
like image 178
scniro Avatar answered Sep 29 '22 05:09

scniro