2016-01-20 23 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(....);