Why is this simple AngularJS ng-show not working?

后端 未结 7 670
旧时难觅i
旧时难觅i 2020-12-13 06:10

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:

相关标签:
7条回答
  • 2020-12-13 06:28

    You want to use apply() function to stop loading message.

    Check this Demo jsFiddle**.

    JavaScript:

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

    Hope this would be help you!

    0 讨论(0)
  • 2020-12-13 06:30

    You need to use $timeout and inject it in your controller:

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

    Fiddle demo

    Edit: removed $scope.apply(); as @Salman suggested

    0 讨论(0)
  • 2020-12-13 06:32

    I 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.

     <div class="mycontent" data-ng-class="{'loaded': !loading}"> 
    

    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.

    .mycontent {
        display: none;
    }
    
    .loaded {
        display: block;
    }
    
    0 讨论(0)
  • 2020-12-13 06:40

    when fire angular event to another object like setTimeout you should use

    $scope.$apply(function(){
         $scope.loading = false;
    });
    

    for example

    var loading={
         show:function(){
            $scope.loading=true
         },
         hide:function(){
            $scope.loading=false
         }
    }  
    

    may not working best way

       var loading={
             show:function(){
                $scope.$apply(function(){
                   $scope.loading=true
                });
             },
             hide:function(){
                $scope.$apply(function(){
                   $scope.loading=false
                });
             }
        } 
    
    0 讨论(0)
  • 2020-12-13 06:41

    A nicer way of doing this is by calling $scope.$digest(); to update your UI

    0 讨论(0)
  • 2020-12-13 06:42

    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);
    }
    
    0 讨论(0)
提交回复
热议问题