步入angularjs directive(指令)--點擊按鈕加入loading狀態

      今天我終於鼓起勇氣寫本身的博客了,激動與懼怕並存,但願你們能多多批評指導,若是可以幫助你們,也但願你們點個贊!!css

用angularjs 工做也有段時間了,整體感受最有挑戰性的仍是指令,由於沒有指令的angularjs 就是隻有骨頭的框架,雖然有不少第三方指令,如:angular Bootstrap,ng-table等,可是根據界面設計的需求,他們遠遠不能知足,怎麼辦??答案只有本身寫了(也能夠google,可是爲了某個小功能,引入一個很大的文件,我是不提倡的。若是老闆想讓你時不時的改改,我估計你會崩潰的,是否是有想辭職的想法,爲了讓工做有意義和提升本身的水平,仍是在時間充足的狀況下本身寫吧!),那麼如今讓咱們開始吧!html

      今天先開始一個入門級的指令:按鈕點擊,加入loading,阻止再次點擊(這在提交表單,ajax請求數據時很是有用);angularjs

      本身小試牛刀,寫了一個(雖然google 不少)。ajax

      

 1 <!DOCTYPE html>
 2 <html ng-app="myApp">
 3 <head lang="en">
 4     <meta charset="UTF-8">
 5     <title></title>
 6     <link href="../../bower_components/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">
 7     <script src="../../bower_components/angular/angular.js"></script>
 8 </head>
 9 <body ng-controller="myCtrl">
10 <button class="btn btn-primary" btn-loading-text="loading" trigger-loading="beginLoading" ng-click="toggleLoad()">load</button>
11 <button class="btn btn-default" ng-click="toggleLoad()">切換按鈕狀態</button>
12 </body>
13 <script>
14     angular.module('myDirectives',[])
15             .directive('triggerLoading',function(){
16                 return {
17                     restrict:'A',
18                     link:function(scope,element,attr){
19                         scope.prevText=element.text();
20                         scope.$watch(function(){
21                             return scope.$eval(attr.triggerLoading);
22                         },function(value){
23                             if(angular.isDefined(value)){
24                                 //element.toggleClass('disabled',value);
25                                 value?element.attr('disabled',true):element.removeAttr('disabled');
26                                 element.text((value?attr.btnLoadingText:scope.prevText));
27                             }
28                         });
29                     }
30                 }
31             });
32             angular.module('myApp',['myDirectives'])
33             .controller('myCtrl',['$scope',function($scope){
34                 $scope.toggleLoad=function(){
35                     $scope.beginLoading=!$scope.beginLoading;
36                 };
37             }]);
38 
39 </script>
40 </html>

     你們能夠複製運行一下,提示:須要修改引入文件的路徑。bootstrap

     這個指令功能很簡單只是點擊加入loading狀態,如何不屑與這個功能,那就別往下看了,直接點贊吧,謝謝!app

     指令這個東西,格式須要記住。框架

     下次首先講講".directive()",謝謝關注!google

相關文章
相關標籤/搜索