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获取TreeView控件选中节点的Text和Value值的方法
Nov 24 Javascript
JavaScript代码复用模式实例分析
Dec 02 Javascript
node.js中使用node-schedule实现定时任务实例
Jun 03 Javascript
实现图片预加载的三大方法及优缺点分析
Nov 19 Javascript
JSONP跨域GET请求解决Ajax跨域访问问题
Dec 31 Javascript
JS实现简易图片轮播效果的方法
Mar 25 Javascript
JQuery中clone方法复制节点
May 18 Javascript
JQuery包裹DOM节点的方法
Jun 11 Javascript
bootstrap学习笔记之初识bootstrap
Jun 21 Javascript
jQuery将表单序列化成一个Object对象的实例
Nov 29 Javascript
AngularJS中的作用域实例分析
May 16 Javascript
vue滚动固定顶部及修改样式的实例代码
May 30 Javascript
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
法国:浪漫之都的咖啡文化
2021/03/03 咖啡文化
PHP4中session登录页面的应用
2008/07/25 PHP
windows环境下php配置memcache的具体操作步骤
2013/06/09 PHP
基于php常用函数总结(数组,字符串,时间,文件操作)
2013/06/27 PHP
CI框架入门示例之数据库取数据完整实现方法
2014/11/05 PHP
php从csv文件读取数据并输出到网页的方法
2015/03/14 PHP
PHP动态生成指定大小随机图片的方法
2016/03/25 PHP
thinkPHP中钩子的两种配置调用方法详解
2016/11/11 PHP
yii框架搜索分页modle写法
2016/12/19 PHP
PHP实现电商订单自动确认收货redis队列
2017/05/17 PHP
让GoogleCode的SVN下的HTML文件在FireFox下正常显示.
2009/05/25 Javascript
关于JavaScript的with 语句的使用方法
2011/05/09 Javascript
jQuery EasyUI API 中文文档 - PropertyGrid属性表格
2011/11/18 Javascript
js判断样式className同时增加class或删除class
2013/01/30 Javascript
JavaScript生成GUID的多种算法小结
2013/08/18 Javascript
全面解析Bootstrap表单使用方法(表单控件)
2015/11/24 Javascript
JQuery form表单提交前验证单选框是否选中、删除记录时验证经验总结(整理)
2017/06/09 jQuery
jQuery easyui datagird编辑行删除行功能的实现代码
2018/09/20 jQuery
JS简单判断是否在微信浏览器打开的方法示例
2019/01/08 Javascript
详解在Javascript中进行面向切面编程
2019/04/28 Javascript
vue.js的简单自动求和计算实例
2019/11/08 Javascript
vue自定义树状结构图的实现方法
2020/10/18 Javascript
Python中栈、队列与优先级队列的实现方法
2019/06/30 Python
django formset实现数据表的批量操作的示例代码
2019/12/06 Python
Python Opencv中用compareHist函数进行直方图比较对比图片
2020/04/07 Python
Numpy一维线性插值函数的用法
2020/04/22 Python
Python gevent协程切换实现详解
2020/09/14 Python
使用AJAX和Django获取数据的方法实例
2020/10/25 Python
html5组织内容_动力节点Java学院整理
2017/07/10 HTML / CSS
S’well Bottle保温杯官网:绝缘不锈钢水瓶
2018/05/09 全球购物
澳大利亚最大的百货公司:Myer
2018/12/21 全球购物
顶撞领导检讨书
2014/01/29 职场文书
《花木兰》教学反思
2014/04/09 职场文书
文体活动总结范文
2014/05/05 职场文书
医院营销工作计划
2015/01/16 职场文书
Python文件的操作示例的详细讲解
2021/04/08 Python