今天我終於鼓起勇氣寫自己的博客了,激動與害怕並存,希望大家能多多批評指導,如果能夠幫助大家,也希望大家點個贊!!
用angularjs 工作也有段時間了,總體感覺最有挑戰性的還是指令,因為沒有指令的angularjs 就是只有骨頭的框架,雖然有很多第三方指令,如:angular Bootstrap,ng-table等,但是根據界面設計的需求,他們遠遠不能滿足,怎么辦??答案只有自己寫了(也可以google,但是為了某個小功能,引入一個很大的文件,我是不提倡的。如果老板想讓你時不時的改改,我估計你會崩潰的,是不是有想辭職的想法,為了讓工作有意義和提高自己的水平,還是在時間充足的情況下自己寫吧!),那么現在讓我們開始吧!
今天先開始一個入門級的指令:按鈕點擊,加入loading,阻止再次點擊(這在提交表單,ajax請求數據時非常有用);
自己小試牛刀,寫了一個(雖然google 很多)。
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>
大家可以復制運行一下,提示:需要修改引入文件的路徑。
這個指令功能很簡單只是點擊加入loading狀態,如何不屑與這個功能,那就別往下看了,直接點贊吧,謝謝!
指令這個東西,格式需要記住。
下次首先講講".directive()",謝謝關注!
