今天我终于鼓起勇气写自己的博客了,激动与害怕并存,希望大家能多多批评指导,如果能够帮助大家,也希望大家点个赞!!
用angularjs 工作也有段时间了,总体感觉最有挑战性的还是指令,因为没有指令的angularjs 就是只有骨头的框架,虽然有很多第三方指令,如:angular Bootstrap,ng-table等,但是根据界面设计的需求,他们远远不能满足,怎么办??答案只有自己写了(也可以google,但是为了某个小功能,引入一个很大的文件,我是不提倡的。如果老板想让你时不时的改改,我估计你会崩溃的,是不是有想辞职的想法,为了让工作有意义和提高自己的水平,还是在时间充足的情况下自己写吧!),那么现在让我们开始吧!
今天先开始一个入门级的指令:按钮点击,加入loading,阻止再次点击(这在提交表单,ajax请求数据时非常有用);
自己小试牛刀,写了一个(虽然google 很多)。
<!DOCTYPE html>
<html ng-app="myApp">
<head lang="en">
<meta charset="UTF-8">
<title></title>
<link href="../../bower_components/bootstrap/dist/css/bootstrap.min.css" rel="external nofollow" rel="stylesheet">
<script src="../../bower_components/angular/angular.js"></script>
</head>
<body ng-controller="myCtrl">
<button class="btn btn-primary" btn-loading-text="loading" trigger-loading="beginLoading" ng-click="toggleLoad()">load</button>
<button class="btn btn-default" ng-click="toggleLoad()">切换按钮状态</button>
</body>
<script>
angular.module('myDirectives',[])
.directive('triggerLoading',function(){
return {
restrict:'A',
link:function(scope,element,attr){
scope.prevText=element.text();
scope.$watch(function(){
return scope.$eval(attr.triggerLoading);
},function(value){
if(angular.isDefined(value)){
//element.toggleClass('disabled',value);
value?element.attr('disabled',true):element.removeAttr('disabled');
element.text((value?attr.btnLoadingText:scope.prevText));
}
});
}
}
});
angular.module('myApp',['myDirectives'])
.controller('myCtrl',['$scope',function($scope){
$scope.toggleLoad=function(){
$scope.beginLoading=!$scope.beginLoading;
};
}]); </script>
</html>
大家可以复制运行一下,提示:需要修改引入文件的路径。
这个指令功能很简单只是点击加入loading状态,如何不屑与这个功能,那就别往下看了,直接点赞吧,谢谢!
指令这个东西,格式需要记住。
下次首先讲讲”.directive()”,谢谢关注!