javascript - 加载器未显示在 Angular js 中的 ajax 请求上

标签 javascript angularjs ajax

因为我使用的是 $http.ajax 请求。由于我对服务器的操作需要时间,因此需要很长时间。我需要在处理请求时显示加载程序,但加载程序不显示。虽然我的代码看起来是正确的。我尝试了不同的方法,但没有成功。

Index.html

<body ng-app="app">

    <!-- loader, can be used on multiple pages-->
    <div class="loading loader-quart" ng-show="isLoading"></div>

<!--         my logic       --> 

</body>

addCtrl.js

//method to get all the attributes and send to server using service
    $scope.add = function () {
        if ($scope.Option == 'newInstance')
            $scope.singleObject.FK_Name = 'MetisEmptyTemplate';
        $rootScope.isLoading = true;
        var featuresList = websiteService.getUpdatedTree($scope.treeDataSource);
        var formData = new Website("", $scope.singleObject.Name, $scope.singleObject.DisplayName, $scope.singleObject.Description, $scope.singleObject.State, "", $scope.singleObject.FK_Name, $scope.singleObject.Email, featuresList);

        websiteService.addwebsite(formData);
        $rootScope.isLoading = false;
    }

websiteService.js

//service to add website
    this.addwebsite = function (website) {
        $http({
            method: 'POST',
            url: $rootScope.url + 'Add',
            data: JSON.stringify(website),
            contentType: 'application/json'
        }).success(function (data) {
            alert(data);
        }).error(function (data, status, headers, config) {
            //alert(data);
        });
    }

因为我要在开始时将 isLoading 设为“true”,然后在请求完成后将 isLoading 设为“false”。代码问题出在哪里?

最佳答案

您的 websiteServices 代码异步执行。这意味着上面的代码将显示加载器,然后立即再次隐藏它。

要在 Controller 中处理异步代码,您必须从服务返回一个 Promise,并使用 .then() 将微调器隐藏在回调函数中。

服务:

this.addwebsite = function (website) {
    var deferred = $q.defer();
    $http({
        method: 'POST',
        url: $rootScope.url + 'Add',
        data: JSON.stringify(website),
        contentType: 'application/json'
    }).success(function (data) {
        alert(data);
        deferred.resolve(data);
    }).error(function (data, status, headers, config) {
        //alert(data);
        deferred.reject(data);
    });
    return deferred.promise
}

Controller :

websiteService.addwebsite(formData).then(function(){
    $rootScope.isLoading = false
});

关于javascript - 加载器未显示在 Angular js 中的 ajax 请求上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40019567/

相关文章:

javascript - 从 contentEditable div 中提取文本

javascript - Firebase 和 Angularjs 范围对象数组未定义

javascript - 从 ng-click 调用 $event 上的 JQuery 函数

jquery 获取/getJSON : call a function after *several* files load?

javascript - 如何将从循环获取的 Ajax 变量附加到 <a href ='' '/a> 标记中

javascript - 从数组的字典 JS 获取数据时出现问题

javascript - 每 10 个芒果去除 1 个芒果

javascript - 从一个对象中删除属性就是从另一个具有相似名称的对象中删除该属性

javascript - 如何在表单验证中使用Angular应用jquery的远程方法?

javascript - 如果条件不满足则提交表单