I cannot figure out why my simple AngularJS app not working as intended. "Loading..." is supposed to be hidden, and "Done!" should be shown after 1 second.
html:
<div ng-app>
<div ng-controller="TestCtrl">
<div class="text-center" ng-show="loading">
<h1>Loading...</h1>
</div>
<div class="text-center" ng-show="!loading">
<h1>Done!</h1>
</div>
</div>
</div>
Javascript:
function TestCtrl($scope) {
$scope.loading = true;
setTimeout(function () {
$scope.loading = false;
}, 1000);
}
I think the biggest problem here is that you are using a primitive as your model. The angular team recommends to use an object to tie your model to. For example:
Then in your html:
That way angular gets a reference to a field inside an object instead of a primitive being pointed to by a variable.
You want to use
apply()
function to stop loading message.Check this Demo jsFiddle**.
JavaScript:
Hope this would be help you!
A nicer way of doing this is by calling
$scope.$digest();
to update your UIYou need to use
$timeout
and inject it in your controller:Fiddle demo
Edit: removed
$scope.apply();
as @Salman suggestedI have found that one way to work around ng-show not evaluating in the way you want it to be is to use ng-class instead.
This way when $scope.loading is not equal to true the css class 'loaded' will be added to the element. Then you just need a to use the css class to show/hide the content.
You need to tell angular that you updated the var:
or just