45

我无法弄清楚为什么我的简单 AngularJS 应用程序无法按预期工作。“正在加载...”应该被隐藏,“完成!” 应在 1 秒后显示。

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

7 回答 7

63

您需要告诉 Angular 您更新了 var:

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

要不就

function TestCtrl($scope, $timeout) {
    $scope.loading = true;
    $timeout(function () {
        $scope.loading = false;
    }, 1000);
}
于 2014-04-05T13:19:17.863 回答
14

一个更好的方法是调用$scope.$digest();来更新你的 UI

于 2014-07-08T14:56:07.613 回答
6

您需要$timeout在控制器中使用并注入它:

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

小提琴演示

编辑: $scope.apply();按照@Salman 的建议删除

于 2014-04-05T13:18:58.067 回答
6

您想使用apply()功能来停止加载消息。

检查这个演示 jsFiddle **。

JavaScript:

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

希望这会对您有所帮助!

于 2014-04-05T13:32:29.307 回答
3

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
            });
         }
    } 
于 2014-08-20T06:38:23.590 回答
1

我发现解决 ng-show 未按照您希望的方式进行评估的一种方法是使用 ng-class 代替。

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

这样,当 $scope.loading 不等于 true 时,css 类“已加载”将被添加到元素中。然后你只需要使用 css 类来显示/隐藏内容。

.mycontent {
    display: none;
}

.loaded {
    display: block;
}
于 2016-08-08T00:48:04.380 回答
0

我认为这里最大的问题是您使用原始模型作为模型。Angular 团队建议使用对象将模型绑定到。例如:

scope.model = {};
scope.model.loading = false;

然后在你的html中:

<div class="text-center" ng-show="model.loading">

这样,角度获取对对象内部字段的引用,而不是变量指向的基元。

于 2018-05-02T21:53:15.043 回答