步入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

相关文章
相关标签/搜索