search

Home  >  Q&A  >  body text

angular.js - How to control the hiding and display of elements by setting the value of ng-show binding in the ajax callback in AngularJS

I have a button and a loading icon on the page. The loading icon uses ng-show to bind a controller attribute to identify whether to display it. When the button is clicked, the program uses $http.post to request data from the background and set the attribute set by ng-show to true. Then set the ng-show attribute to false in the callback to hide the loading icon. My problem is that the property value set in the callback does not hide the loading icon. When I first started using angularjs, there were many problems that were not very clear to me. Can anyone help me solve the whole problem?
The code snippet is as follows:

    <!-- 页面html片段-->
    <p class="col-sm-offset-2 col-sm-10">
        <button class="btn btn-primary" ng-disabled="groupForm.$invalid" ng-click="saveGroup()">
              保存<i class="fa fa-refresh fa-spin fa-lg fa-fw" ng-show="showLoading"></i>
        </button>
    </p>
//js controller代码

var teamModule = angular.module("TeamModule", []);

teamModule.controller('GroupCtrl', function($scope, $http, $state, $stateParams) {
    
    $scope.showLoading = false;
    $scope.groupInfo = {};
    
    $scope.toggleLoading = function(isShow){
        $scope.showLoading = isShow;
    };
    
    $scope.saveGroup = function(){
        $scope.toggleLoading(true);
        
        //请求使用jquery进行发送
        $.ajax({
            url: 'group/save',
            data: $scope.groupInfo,
            dataType: 'json',
            type: "post", 
            success: function(data){
                console.log(data);
                $scope.toggleLoading(false);
            },
            error: function(){
                $scope.toggleLoading(false);
            }
        });
        
    };

});
仅有的幸福仅有的幸福2805 days ago625

reply all(2)I'll reply

  • 漂亮男人

    漂亮男人2017-05-15 17:05:13

    Come and do it with me

    $.ajax({
        url: 'group/save',
        data: $scope.groupInfo,
        dataType: 'json',
        type: "post",
        success: function(data){
            console.log(data);
            $scope.toggleLoading(false);
            $scope.$apply();
        }, error: function(){
            $scope.toggleLoading(false);
            $scope.$apply();
        }
    });

    reply
    0
  • 天蓬老师

    天蓬老师2017-05-15 17:05:13

    angularjs has its own $http

    $http({
        url:'/api/login.do',//请求地址
        data:{username:'test',password:'test'},//post数据
        params:{version:1}//get参数
    }).success(function(data){
        console.log(data);
    }).error(function(e){
        console.error(e);
    });

    If you use jquery’s $ajax, you need to pay attention to the $scope.$apply function. The standard usage is as follows:

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

    reply
    0
  • Cancelreply