Reputation: 5059
New to AngularJSs. Wondering why setTimeout
is not working. Is it true that it doe snot work with AngularJS?
<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.
Upvotes: 5
Views: 6971
Reputation: 295
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.
Upvotes: 4
Reputation: 16979
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) {
....
}]);
Upvotes: 8