2016-01-20 25 views
0

我想编写一个指令,在http请求期间保持按钮和页面禁用。如何禁用按钮,直到在AngularJS中处理/加载http请求?

  • 如果我更新或提交表单,该按钮将禁用,直到HTTP响应 完成。

  • 加载页面时,它将禁用,直到从服务器加载的整个数据为 。

  • 10秒后,该按钮将处于活动状态,用户可以多次点击 。

app.js

<script> 
var angModule = angular.module("myApp", []); 

angModule.controller("myCtrl", function ($scope, $timeout) { 
    $scope.isSaving = undefined; 
    $scope.btnVal = 'Yes'; 
    $scope.save = function() 
    { 
    $scope.isSaving = true; 

    $timeout(function() 
    { 
     $scope.isSaving = false; 

    }, 1000); 
    }; 
}); 
</script> 

的index.html

<div ng-app="myApp"> 
    <ng-form ng-controller="myCtrl"> 
    Saving: {{isSaving}}    

     <button ng-click="save()" ng-disabled="isSaving"> 
    <span ng-hide="isSaving">Save</span> 
    <span ng-show="isSaving">Loading...</span><i class="fa fa-spinner fa-spin" ng-show="isSaving"></i> 
     </button> 


    </ng-form> 
</div> 

我是新来AngularJS,请帮我写了这样的指令。

+0

你可以找到如何创建自定义指令非常有用的信息[这里](https://docs.angularjs.org/guide/directive) – Filipe

回答

1

这里一个基本的例子:

<button ng-click="save()" loading="Loading..." notloading="save" disableonrequest> 

myApp.directive("disableonrequest", function($http) { 
    return function(scope, element, attrs) { 
    scope.$watch(function() { 
     return $http.pendingRequests.length > 0; 
    }, function(request) { 
     if (!request) { 
     element.html("<span >"+attrs.notloading+"</span>"); 
     } else { 
     element.html("<span >"+attrs.loading+"</span><i class='fa fa-spinner fa-spin'></i>"); 
     } 
    }); 
    } 
}); 

A WORKING EXAMPLE

+0

三江源Vanojx1问题是如何它将成为一个可重用的代码,它将只应用按钮名称作为保存并在处理它时将其加载.. –

+0

谢谢Vanojx1的问题是它如何成为一个可重用的代码,它将只应用按钮名称作为保存,并在处理时将其加载。 。我想在同一个地方使用很多地方。但是按钮名称在请求前后发生了变化例如,我需要将我的按钮名称作为Login,并在处理它时将其更改为Processing ..而不是Loading .. –

+0

@ Symon-kt检查我的编辑 – Vanojx1

0

根据您的需求,您可能不一定需要为这个简单的任务自定义指令。

您可以简单地在$http的回调中设置$scope.isSaving属性。

例如

$http({ 
     url: 'http://path/to/the/api/', 
     method: 'GET', 
     headers: { 
      'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8', 
     } 
    }) 
    .success(function(data, status){ 
     $scope.isSaving = false; 
    }) 
    .error(....);