步入angularjs directive(指令)--点击按钮加入loading状态

      今天我终于鼓起勇气写自己的博客了,激动与害怕并存,希望大家能多多批评指导,如果能够帮助大家,也希望大家点个赞!!

用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()",谢谢关注!

posted @ 2016-06-26 13:12  zhanglearning  阅读(3831)  评论(0编辑  收藏  举报