我正在使用此指令在$ http服务请求上显示'loading'分区。
var module = angular.module('my-app', ['onsen', 'ngAnimate', 'ngMessages']);
module.directive('loading', ['$http', function ($http) {
return {
restrict: 'AE',
link: function ($scope, element, attrs, ctrl) {
$scope.isLoading = function () {
return ($http.pendingRequests.length > 0);
};
$scope.$watch($scope.isLoading, function (v) {
if (v) {
element.removeClass('ng-hide');
} else {
element.addClass('ng-hide');
}
});
}
};
<body ng-controller="BodyController">
<div loading class="spinner-container">
<img src="images/loading.svg" class="spinner" />
</div>
</body>
如果正在执行此特定功能,则要禁用它。
module.controller('BodyController', function ($scope, $http, $interval) {
$scope.getNotificationCount = function () {
var url="http://stackoverflow.com" // any url, stackoverflow is an example
var query = "";
$http({
method: 'POST',
url: url,
data: query,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).
success(function (data) {
console.log("success");
}).error(function (data) {
console.log("error");
});
};
$interval($scope.getNotificationCount,30000);
});
我想要这个,因为我在$ interval()中调用了getNotificationCount()函数,我不想再次在屏幕上显示我的自定义加载html div。
有没有办法实现这个目标?帮助我。
答案 0 :(得分:2)
module.directive('loading', ['$http', function ($http) {
return {
restrict: 'AE',
scope : {
isDisabled : '=' // Added new attribute to disable and enable the directive
},
link: function ($scope, element, attrs, ctrl) {
$scope.isLoading = function () {
return ($http.pendingRequests.length > 0);
};
$scope.$watch($scope.isLoading, function (v) {
if(!scope.isDisabled){
// Do things only when isDisabled property is false
if (v) {
element.removeClass('ng-hide');
} else {
element.addClass('ng-hide');
}
}
});
}
};
你的html代码应该是,
<body ng-controller="BodyController">
<div loading is-disabled="isLoaderDisabled" class="spinner-container">
<img src="images/loading.svg" class="spinner" />
</div>
</body>
此处,isLoaderDisabled
是范围变量。现在,您可以通过将true
或false
设置为范围变量$scope.isLoaderDisabled
来禁用和启用您的指令。
$scope.isLoaderDisabled = false; // Initialize
module.controller('BodyController', function ($scope, $http, $interval) {
$scope.isLoaderDisabled = true; // disable your loading directive
$scope.getNotificationCount = function () {
var url="http://stackoverflow.com" // any url, stackoverflow is an example
var query = "";
$http({
method: 'POST',
url: url,
data: query,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).
success(function (data) {
console.log("success");
}).error(function (data) {
console.log("error");
$scope.isLoaderDisabled = false; // enable your directive
});
};
$interval($scope.getNotificationCount,30000);
});
您应该在每个成功函数上启用您的指令。