Angular 常用指令实例总结整理


Posted in Javascript onDecember 13, 2016

Angular 常用指令

已经用了angular很久积累了一些很实用的指令,需要的话直接拿走用,有问题大家一起交流

1.focus时,input:text内容全选

angular.module('my.directives').directive('autoselect', [function () {
  return {
    restrict: 'A',
    link: function (scope, element, attr) {
      if (element.is("input") && attr.type === "text") {
        var selected = false;
        var time = parseInt(attr["autoselect"]);
        element.bind("mouseup", function (e) {
          if (selected) {
            e.preventDefault();
            e.stopPropagation();
          }
          selected = false;
        });
        if (time > 0) {
          element.bind("focus", function (event) {
            setTimeout(function () {
              selected = true;
              event.target.select();
            }, time);
          });
        } else {
          element.bind("focus", function (event) {
            selected = true;
            event.target.select();
          });

        }
      }
    }
  };
}]);

2.clickOutside指令,外部点击时触发,click-outside="func()" func为自己指定的方法,一般为关闭当前层的方法,inside-id="" 点击指定id的输入框时,当前层不关闭

angular.module('my.directives').directive('clickOutside', ['$document', function ($document) {
  return {
    restrict: 'A',
    link: function (scope, element, attrs) {
      $(element).bind('mousedown', function (e) {
        e.preventDefault();
        e.stopPropagation();
      });

      $("#" + attrs["insideId"]).bind('mousedown', function (e) {
        e.stopPropagation();
      });

      $("#" + attrs["insideId"]).bind('blur', function (e) {
        setTimeout(function () {
          scope.$apply(attrs.clickOutside);
        });
      });

      $document.bind('mousedown', function () {
        scope.$apply(attrs.clickOutside);
      });
    }
  };
}]);

3.clickInside指令,内部点击时触发

angular.module('my.directives').directive('clickInside', ['$document', function ($document) {
  return {
    restrict: 'A',
    link: function (scope, element, attrs, ctrl) {
      $(element).bind('focus click', function (e) {
        scope.$apply(attrs.clickInside);
        e.stopPropagation();
      });
    }
  };
}]);

4.scrollInside 指令 ,内部滚动时触发

angular.module('my.directives').directive('scrollInside', function () {
  return {
    restrict: 'A',
    link: function (scope, element, attrs, ctrl) {
      $(element).bind('scroll', function (e) {
        scope.$apply(attrs.scrollInside);
        e.stopPropagation();
      });
    }
  };
});

5. bindKeyBoardEvent指令,内部获得焦点或者点击时触发

angular.module('my.directives').directive('bindKeyBoardEvent', function () {
  return {
    restrict: 'A',
    link: function (scope, element, attrs, ctrl) {
      $(element).bind('focus click', function (e) {
        scope.$apply(attrs.bindKeyBoardEvent);
        e.stopPropagation();
      });
    }
  };
});

6. myDraggable 使元素可拖动

angular.module('my.directives').directive('myDraggable', ['$parse', function ($parse) {
  return {
    restrict: 'A',
    link: function (scope, element, attr) {
      if (attr["modal"] !== undefined) {
        scope.$watch(attr["modal"], function (newValue) {
          if (newValue) {
            setTimeout(function () {
              $(".modal").draggable({handle: ".modal-header"});
            }, 100);
          } else {
            $(".modal").attr("style", "");
          }
        }, true);
        $(window).resize(function () {
          $(".modal").attr("style", "");
        });
      } else {
        element.draggable($parse(attr["hrDraggable"])(scope));
      }
    }
  };
}]);

6.myResizable 使元素可拖拽改变尺寸大小

angular.module('my.directives').directive('myResizable', ['$parse', function ($parse) {
  return {
    restrict: 'A',
    link: function (scope, element, attr) {
      if (attr["modal"] !== undefined) {
        scope.$watch(attr["modal"], function (newValue) {
          if (newValue) {
            setTimeout(function () {
              $(".modal").resizable({handles: "e, w"});
            }, 100);
          }
        }, true);
      } else {
        element.resizable($parse(attr["hrResizable"])(scope));
      }
    }
  };
}]);

6. conditionFocus 作为一个元素的属性存在:如果监听的表达式值为true,则将焦点放到本元素上。

angular.module('my.directives').directive("conditionFocus", [function () {
  return function (scope, element, attrs) {
    var dereg = scope.$watch(attrs.conditionFocus, function (newValue) {
      if (newValue) {
        element.focus();
      }
    });
    element.bind("$destroy", function () {
      if (dereg) {
        dereg();
      }
    });
  };
}]);

7.scrollToHide 滚动到顶部的时候触发

angular.module('my.directives').directive("scrollToHide", [function () {
  return function (scope, element, attrs) {
    var height= parseFloat(attrs.maxHeight)
    $(window).scroll(function(){
      var scrollTop= document.body.scrollTop||document.documentElement.scrollTop;
       if(scrollTop>height){
         $parse(attrs.ngShow).assign(scope, false);
       }else{
         $parse(attrs.ngShow).assign(scope, true);
       }


    })

  };
}]);

8.resetToZero 作为一个元素的属性存在:如果监听的表达式值为true,则将本元素中所绑定的ngModel值设为0

angular.module('my.directives').directive("resetToZero", ["$parse", function ($parse) {
  return function (scope, element, attrs) {
    var dereg = scope.$watch(attrs.resetToZero, function (newValue) {
      if (newValue) {
        if (attrs.ngModel) {
          $parse(attrs.ngModel).assign(scope, 0);
        }
      }
    });
    element.bind("$destroy", function () {
      if (dereg) {
        dereg();
      }
    });
  };
}]);

9.resetToEmptyString 作为一个元素的属性存在:如果监听的表达式值为true,则将本元素中所绑定的ngModel值设为空字符串。

angular.module('my.directives').directive("resetToEmptyString", ["$parse", function ($parse) {
  return function (scope, element, attrs) {
    var dereg = scope.$watch(attrs.resetToEmptyString, function (newValue) {
      if (newValue) {
        if (attrs.ngModel) {
          var _getter = $parse(attrs.ngModel);
          if (_getter(scope)) {
            _getter.assign(scope, "");
          } else {
            _getter.assign(scope.$parent, "");
          }
        }
      }
    });
    element.bind("$destroy", function () {
      if (dereg) {
        dereg();
      }
    });
  };
}]);

10. numberOnly 输入框内容仅限数值的指令(输入内容不允许为 负值),可以设定最大值(max属性)

angular.module('my.directives').directive("numberOnly", ["$parse", function ($parse) {
  return function (scope, element, attrs) {
    element.bind("keyup", function () {
      if(event.keyCode==37||event.keyCode== 39){
        return false;
      }
      var val = element.val().replace(/[^\d.]/g, '');
      if(attrs.max){
        if(val>parseInt(attrs.max)){
          val=attrs.max;
        }
      }
      element.val(val);
      if (attrs.ngModel) {
        $parse(attrs.ngModel).assign(scope, val);
      }
      return false;
    });
    element.bind("afterpaste", function () {
      var val = element.val().replace(/[^\d.]/g, '');
      if(attrs.max){
        if(val>parseInt(attrs.max)){
          val=attrs.max;
        }
      }
      element.val(val);
      if (attrs.ngModel) {
        $parse(attrs.ngModel).assign(scope, val);
      }
      return false;
    });
  };
}]);

11. upperCaseOnly 输入框自动转换成大写

angular.module('my.directives').directive("upperCaseOnly", ["$parse", function ($parse) {
  return function (scope, element, attrs) {
    element.bind("keyup", function () {
      var val = element.val().toUpperCase();
      element.val(val);
      if (attrs.ngModel) {
        $parse(attrs.ngModel).assign(scope, val);
      }
      return false;
    });
    element.bind("afterpaste", function () {
      var val =element.val().toUpperCase();
      element.val(val);
      if (attrs.ngModel) {
        $parse(attrs.ngModel).assign(scope, val);
      }
      return false;
    });
  };
}]);

12. noSpecialString 输入框内容不能为特殊字符

angular.module('my.directives').directive("noSpecialString", ["$parse", function ($parse) {
  return function (scope, element, attrs) {
    element.bind("keyup", function () {
      var val = element.val().replace(/[\W]/g, '');
      element.val(val);
      if (attrs.ngModel) {
        $parse(attrs.ngModel).assign(scope, val);
      }
      return false;
    });
    element.bind("afterpaste", function () {
      var val = element.val().replace(/[^\d]/g, '');
      element.val(val);
      if (attrs.ngModel) {
        $parse(attrs.ngModel).assign(scope, val);
      }
      return false;
    });
  };
}]);

13. round2bit 输入框失去焦点 保留两位小数

angular.module('my.directives').directive("round2bit", ['$parse', '$filter', function ($parse, $filter) {
  return function ($scope, element, attrs) {
    element.blur(function () {
      if (attrs.ngModel) {
        var _getter = $parse(attrs.ngModel);
        var _numberStr2Round = (_getter($scope) || 0);
        _getter.assign($scope, $filter('number')(_numberStr2Round, 2).split(",").join(""));
        $scope.$apply();
      }
    });
  };
}]);

14.SelfHeight dom编译期设置元素高度,可以接受数字或者表达式

angular.module('hr.directives').directive('SelfHeight', ['$timeout', function ($timeout) {
  function _resizeElement(element, SelfHeight) {
    element.height((typeof SelfHeight === "number") ? SelfHeight : eval(SelfHeight));
  };

  return {
    priority: 1000,
    link: function (scope, element, attrs) {
      var hrSelfHeight = attrs["SelfHeight"];
      var on = attrs["on"];
      if (on) {
        $(window).resize(function () {
          _resizeElement(element, scope.$eval(SelfHeight));
        });
        scope.$watch(on, function () {
          $timeout(function () {
            _resizeElement(element, scope.$eval(SelfHeight));
          }, 100);
        }, true);
      } else {
        $(window).resize(function () {
          _resizeElement(element, SelfHeight);
        });
        _resizeElement(element, SelfHeight);
      }
    }
  };
}]);

 感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

Javascript 相关文章推荐
Js获取下拉框选定项的值和文本的实现代码
Feb 26 Javascript
整理AngularJS框架使用过程当中的一些性能优化要点
Mar 05 Javascript
JavaScript基础教程——入门必看篇
May 20 Javascript
全面介绍javascript实用技巧及单竖杠
Jul 18 Javascript
vue双向绑定的简单实现
Dec 22 Javascript
js 两数组去除重复数值的实例
Dec 06 Javascript
基于vue v-for 多层循环嵌套获取行数的方法
Sep 26 Javascript
Vuex modules模式下mapState/mapMutations的操作实例
Oct 17 Javascript
javascript设计模式 ? 抽象工厂模式原理与应用实例分析
Apr 09 Javascript
JavaScript实现手机号码 3-4-4格式并控制新增和删除时光标的位置
Jun 02 Javascript
vue组件讲解(is属性的用法)模板标签替换操作
Sep 04 Javascript
使用这 6个Vue加载动画库来减少我们网站的跳出率
May 18 Vue.js
jQuery UI制作选项卡(tabs)
Dec 13 #Javascript
详解Bootstrap各式各样的按钮(推荐)
Dec 13 #Javascript
javascript动画系列之模拟滚动条
Dec 13 #Javascript
js闭包用法实例详解
Dec 13 #Javascript
深入学习Bootstrap表单
Dec 13 #Javascript
ThinkJS中如何使用MongoDB的CURD操作
Dec 13 #Javascript
Bootstrap Img 图片样式(推荐)
Dec 13 #Javascript
You might like
php中将字符串转为HTML的实体引用的一个类
2013/02/03 PHP
PHP中的替代语法简介
2014/08/22 PHP
WordPress的文章自动添加关键词及关键词的SEO优化
2016/03/01 PHP
JavaScript定义类或函数的几种方式小结
2011/01/09 Javascript
Javascript中arguments对象详解
2014/10/22 Javascript
jQuery修改li下的样式以及li下的img的src的值的方法
2014/11/02 Javascript
jquery实现动态画圆
2014/12/04 Javascript
jQuery中大家不太了解的几个方法
2015/03/04 Javascript
浅谈jQuery页面的滚动位置scrollTop、scrollLeft
2015/05/19 Javascript
微信小程序 Template详解及简单实例
2017/01/05 Javascript
canvas实现图像布局填充功能
2017/02/06 Javascript
layui监听单元格编辑前后交互的例子
2019/09/16 Javascript
解决vue项目 build之后资源文件找不到的问题
2020/09/12 Javascript
ant design pro中可控的筛选和排序实例
2020/11/17 Javascript
JavaScript使用setTimeout实现倒计时效果
2021/02/19 Javascript
Python和Ruby中each循环引用变量问题(一个隐秘BUG?)
2014/06/04 Python
整理Python中的赋值运算符
2015/05/13 Python
利用python爬取散文网的文章实例教程
2017/06/18 Python
caffe binaryproto 与 npy相互转换的实例讲解
2018/07/09 Python
python安装twisted的问题解析
2018/08/21 Python
Django框架会话技术实例分析【Cookie与Session】
2019/05/24 Python
在线课程:Skillshare
2019/04/02 全球购物
主要的Ajax框架都有什么
2013/11/14 面试题
广告学专业应届生求职信
2013/10/01 职场文书
大学生简历的个人自我评价
2013/12/04 职场文书
我与祖国共奋进演讲稿
2014/09/13 职场文书
2015年学校后勤工作总结
2015/04/08 职场文书
迎新生欢迎词2015
2015/07/16 职场文书
初中团支书竞选稿
2015/11/21 职场文书
2016中秋晚会开幕词
2016/03/03 职场文书
解决Pytorch修改预训练模型时遇到key不匹配的情况
2021/06/05 Python
MySQL 常见的数据表设计误区汇总
2021/06/07 MySQL
Redis中有序集合的内部实现方式的详细介绍
2022/03/16 Redis
js 实现验证码输入框示例详解
2022/09/23 Javascript
Python 第三方库 openpyxl 的安装过程
2022/12/24 Python