AngularJS - 显示/隐藏加载器

AngularJS - Show / Hide Loader

本文关键字:加载 隐藏 显示 AngularJS      更新时间:2023-09-26

>关于angularJS中"scope"的问题我尝试在进行搜索时显示加载动画。

在我的控制器中,我创建了一个名为"加载器"的变量在 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);
    }
}

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

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

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