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 相关文章推荐
强大的jquery插件jqeuryUI做网页对话框效果!简单
Apr 14 Javascript
jquery prop的使用介绍及与attr的区别
Dec 19 Javascript
js获取指定日期周数以及星期几的小例子
Jun 27 Javascript
仿淘宝TAB切换搜索框搜索切换的相关内容
Sep 21 Javascript
在JavaScript中用getMinutes()方法返回指定的分时刻
Jun 10 Javascript
jquery validate demo 基础
Oct 29 Javascript
Bootstrap所支持的表单控件实例详解
May 16 Javascript
js注入 黑客之路必备!
Sep 14 Javascript
Bootstrap3 图片(响应式图片&图片形状)
Jan 04 Javascript
详解Vue CLI 3.0脚手架如何mock数据
Nov 23 Javascript
解决基于 keep-alive 的后台多级路由缓存问题
Dec 23 Javascript
Vue3中的Refs和Ref详情
Nov 11 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
十大催泪虐心动漫电影,有几部你还没看
2020/03/04 日漫
php将数据库导出成excel的方法
2010/05/07 PHP
PHP下通过file_get_contents的代理使用方法
2011/02/16 PHP
php模拟post行为代码总结(POST方式不是绝对安全)
2012/02/22 PHP
PHP简单遍历对象示例
2016/09/28 PHP
PHP与jquery实时显示网站在线人数实例详解
2016/12/02 PHP
PHP通过文件路径获取文件名的实例代码
2018/10/14 PHP
javascript delete 使用示例代码
2010/03/29 Javascript
JQuery CheckBox(复选框)操作方法汇总
2015/04/15 Javascript
jQuery插件slider实现拖动滑块选取价格范围
2015/04/30 Javascript
jQuery+HTML5美女瀑布流布局实现方法
2015/09/21 Javascript
JavaScript String 对象常用方法详解
2016/05/13 Javascript
jQuery基于排序功能实现上移、下移的方法
2016/11/26 Javascript
js获取当前周、上一周、下一周日期
2017/03/19 Javascript
bootstrap suggest搜索建议插件使用详解
2017/03/25 Javascript
Vue 自定义动态组件实例详解
2018/03/28 Javascript
vuex 项目结构目录及一些简单配置介绍
2018/04/08 Javascript
微信小程序--获取用户地理位置名称(无须用户授权)的方法
2019/04/29 Javascript
简单通过settimeout看javascript的运行机制
2019/05/10 Javascript
简单了解JavaScript中常见的反模式
2019/06/21 Javascript
vue+openlayers绘制省市边界线
2020/12/24 Vue.js
[01:38]【DOTA2亚洲邀请赛】Sumail——梦开始的地方
2017/03/03 DOTA
利用Python画ROC曲线和AUC值计算
2016/09/19 Python
利用Python批量压缩png方法实例(支持过滤个别文件与文件夹)
2017/07/30 Python
2018年Python值得关注的开源库、工具和开发者(总结篇)
2018/01/04 Python
python try 异常处理(史上最全)
2019/03/07 Python
Python with关键字,上下文管理器,@contextmanager文件操作示例
2019/10/17 Python
python科学计算之scipy——optimize用法
2019/11/25 Python
python实现udp聊天窗口
2020/03/31 Python
python实现音乐播放和下载小程序功能
2020/04/26 Python
期末自我鉴定
2014/02/02 职场文书
舞蹈毕业生的自我评价
2014/03/05 职场文书
面试必备的求职信
2014/05/25 职场文书
委托公证书样本
2015/01/23 职场文书
个人工作总结怎么写?
2019/04/09 职场文书
Python爬取奶茶店数据分析哪家最好喝以及性价比
2022/09/23 Python