首页 > 如何在 AngularJS 在ajax回调里通过设置ng-show绑定的值来控制元素的隐藏和显示

如何在 AngularJS 在ajax回调里通过设置ng-show绑定的值来控制元素的隐藏和显示

我在页面上有一个按钮和一个loading图标。loading图标使用ng-show绑定一个控制器属性来标识是否显示,当点击按钮时程序使用$http.post去后台请求数据并设置ng-show设置的属性为true。然后在回调中设置ng-show的属性为false来隐藏loading图标。我的问题是在回调中设置的属性值不能隐藏loading图标。刚开始用angularjs有很多问题还不是很清楚,谁能帮帮我解决整个问题。
代码片段如下:

    <!-- 页面html片段-->
    <div 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>
    </div>
//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);
            }
        });
        
    };

});

angularjs有自带的$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);
});

如果使用jquery的$ajax,需要注意的是$scope.$apply函数,标准用法如下:

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

来,跟我一起做

$.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();
    }
});
【热门文章】
【热门文章】