darktideac darktideac - 4 months ago 19
AngularJS Question

Why is this simple AngularJS ng-show not working?

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);
}

Answer

You need to tell angular that you updated the var:

function TestCtrl($scope) {
    $scope.loading = true;
    setTimeout(function () {
        $scope.$apply(function(){
            $scope.loading = false;
        });
    }, 1000);
}

or just

function TestCtrl($scope, $timeout) {
    $scope.loading = true;
    $timeout(function () {
        $scope.loading = false;
    }, 1000);
}