【问题标题】:AngularJS - Show / Hide LoaderAngularJS - 显示/隐藏加载器
【发布时间】:2013-11-15 15:54:02
【问题描述】:

关于angularJS中“范围”的问题 我尝试在搜索时显示加载动画。

在我的控制器中,我创建了一个名为“loader”的变量 在 HTML 中,我将 ng-show="loader" 放在我想显示/隐藏的 div 上

简单...但是...

我可以显示加载器但不能隐藏它...

这是我的代码...

HTML:

 <secion ng-controller="ContactsCtrl">
    <div class="loader" ng-show="loading"></div>

    <h2>Contacts</h2>

    <form class="form-search">
        <input type="text" ng-model="s_search" placeholder="Search for a contact...">
        <button type="submit" class="btn" ng-click="search()">Search</button>    
    </form>

    <div id="resultContact"></div>

</section>

JS:

function ContactsCtrl($scope){
    $scope.loading = false;

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

    $scope.search = function() {
        $scope.loading = true;

        setTimeout($scope.endLoading, 1000);
    }
}

我想问题出在“范围继承”上,但我没有看到我的错误

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    每当您在 Angular 之外调用 Angular 时(例如 jQuery 事件处理程序或此处为 setTimeout()),您都需要调用 $scope.$apply()。但最好的方法是使用 Angular 服务,$timeout (docs) 执行相同的工作调用$apply

    【讨论】:

    • 使用 $timeout 还可以让您测试您的代码。
    【解决方案2】:

    setTimeout 在 Angular 的摘要周期之外。您需要使用 $timeout 来提醒有关您的功能的角度。

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

    我想指出,您似乎正在执行某种“加载”,这意味着使用 $http 或其他数据查找。您可以将函数绑定到完成事件,或者在更改的数据上设置观察者,而不是设置计时器。

    例如:

    $scope.$watch("searchData", function () {
      $scope.loading = false;
    }, true);
    
    
    $scope.$search = function () {
      $scope.loading = true;
    
      $http.get("/searchUrl", function (res) {
        $scope.searchData = res;
      });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-11
      • 2017-08-02
      • 2017-01-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多