问题描述
我在页面上有一个按钮和一个loading图标。loading图标使用ng-show绑定一个控制器属性来标识是否显示,当点击按钮时程序使用$http.post去后台请求数据并设置ng-show设置的属性为true。然后在回调中设置ng-show的属性为false来隐藏loading图标。我的问题是在回调中设置的属性值不能隐藏loading图标。刚开始用angularjs有很多问题还不是很清楚,谁能帮帮我解决整个问题。代码片段如下:
<!-- 页面html片段--> <p class='col-sm-offset-2 col-sm-10'><button ng-disabled='groupForm.$invalid' ng-click='saveGroup()'> 保存<i 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); }}); };});
问题解答
回答1:来,跟我一起做
$.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(); }});回答2:
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;});