我在頁(yè)面上有一個(gè)按鈕和一個(gè)loading圖標(biāo)。loading圖標(biāo)使用ng-show綁定一個(gè)控制器屬性來(lái)標(biāo)識(shí)是否顯示,當(dāng)點(diǎn)擊按鈕時(shí)程序使用$http.post去后臺(tái)請(qǐng)求數(shù)據(jù)并設(shè)置ng-show設(shè)置的屬性為true。然后在回調(diào)中設(shè)置ng-show的屬性為false來(lái)隱藏loading圖標(biāo)。我的問(wèn)題是在回調(diào)中設(shè)置的屬性值不能隱藏loading圖標(biāo)。剛開(kāi)始用angularjs有很多問(wèn)題還不是很清楚,誰(shuí)能幫幫我解決整個(gè)問(wèn)題。
代碼片段如下:
<!-- 頁(yè)面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);
//請(qǐng)求使用jquery進(jìn)行發(fā)送
$.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);
}
});
};
});
來(lái),跟我一起做
$.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();
}
});
angularjs有自帶的$http
$http({
url:'/api/login.do',//請(qǐng)求地址
data:{username:'test',password:'test'},//post數(shù)據(jù)
params:{version:1}//get參數(shù)
}).success(function(data){
console.log(data);
}).error(function(e){
console.error(e);
});
如果使用jquery的$ajax,需要注意的是$scope.$apply函數(shù),標(biāo)準(zhǔn)用法如下:
$scope.$apply(function(){
$scope.loading = false;
});