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实多级联动下拉菜单类,简单实现省市区联动菜单!
May 03 Javascript
js加解密 脚本解密
Feb 22 Javascript
jquery 1.4.2发布!主要是性能与API
Feb 25 Javascript
JavaScript实现生成GUID(全局统一标识符)
Sep 05 Javascript
使用javaScript动态加载Js文件和Css文件
Oct 24 Javascript
Bootstrap select下拉联动(jQuery cxselect)
Jan 04 Javascript
JavaScript html5利用FileReader实现上传功能
Mar 27 Javascript
教你如何用node连接redis的示例代码
Jul 12 Javascript
koa大型web项目中使用路由装饰器的方法示例
Apr 02 Javascript
微信小程序云开发实现增删改查功能
May 17 Javascript
vue 路由meta 设置导航隐藏与显示功能的示例代码
Sep 04 Javascript
vue实现简单数据双向绑定
Apr 28 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
jquery用offset()方法获得元素的xy坐标
2014/09/06 Javascript
一分钟理解js闭包
2016/05/04 Javascript
辨析JavaScript中的Undefined类型与null类型
2016/05/26 Javascript
基于Vue.js实现数字拼图游戏
2016/08/02 Javascript
Chrome浏览器的alert弹窗禁止再次弹出后恢复的方法
2016/12/30 Javascript
JS验证不重复验证码
2017/02/10 Javascript
JQuery中Ajax的操作完整例子
2017/03/07 Javascript
Node接收电子邮件的实例代码
2017/07/21 Javascript
js实现复制功能(多种方法集合)
2018/01/06 Javascript
node内置调试方法总结
2018/02/22 Javascript
jQuery实现动画、消失、显现、渐出、渐入效果示例
2018/09/06 jQuery
CKEditor4配置与开发详细中文说明文档
2018/10/08 Javascript
vue实现父子组件之间的通信以及兄弟组件的通信功能示例
2019/01/29 Javascript
使用koa2创建web项目的方法步骤
2019/03/12 Javascript
详解Bootstrap 学习(一)入门
2019/04/12 Javascript
nodejs实现的http、https 请求封装操作示例
2020/02/06 NodeJs
[02:49]2018DOTA2亚洲邀请赛主赛事决赛日战况回顾 Mineski鏖战5局夺得辉耀
2018/04/10 DOTA
在Python中操作列表之list.extend()方法的使用
2015/05/20 Python
Python中的super()方法使用简介
2015/08/14 Python
详解Python使用simplejson模块解析JSON的方法
2016/03/24 Python
python语言使用技巧分享
2016/05/31 Python
Ubuntu下创建虚拟独立的Python环境全过程
2017/02/10 Python
python 机器学习之支持向量机非线性回归SVR模型
2019/06/26 Python
Windows10下 python3.7 安装 facenet的教程
2019/09/10 Python
python传到前端的数据,双引号被转义的问题
2020/04/03 Python
pytorch 计算ConvTranspose1d输出特征大小方式
2020/06/23 Python
Python装饰器结合递归原理解析
2020/07/02 Python
Python高阶函数与装饰器函数的深入讲解
2020/11/10 Python
澳大利亚百货公司:David Jones
2018/02/08 全球购物
高中毕业生生活的自我评价
2013/12/08 职场文书
教育技术职业规划范文
2014/03/04 职场文书
群众路线党课主持词
2014/04/01 职场文书
租房协议书范本
2014/04/09 职场文书
高中语文课后反思
2014/04/27 职场文书
2015财务年终工作总结范文
2015/05/22 职场文书
在Windows下安装配置CPU版的PyTorch的方法
2021/04/02 Python