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"];
      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);
      }
    }
  };
}]);


 

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

标签:
Angular,常用指令,Angular,常用指令实例,Angular,常用指令整理

免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
评论“Angular 常用指令实例总结整理”
暂无“Angular 常用指令实例总结整理”评论...

《魔兽世界》大逃杀!60人新游玩模式《强袭风暴》3月21日上线

暴雪近日发布了《魔兽世界》10.2.6 更新内容,新游玩模式《强袭风暴》即将于3月21 日在亚服上线,届时玩家将前往阿拉希高地展开一场 60 人大逃杀对战。

艾泽拉斯的冒险者已经征服了艾泽拉斯的大地及遥远的彼岸。他们在对抗世界上最致命的敌人时展现出过人的手腕,并且成功阻止终结宇宙等级的威胁。当他们在为即将于《魔兽世界》资料片《地心之战》中来袭的萨拉塔斯势力做战斗准备时,他们还需要在熟悉的阿拉希高地面对一个全新的敌人──那就是彼此。在《巨龙崛起》10.2.6 更新的《强袭风暴》中,玩家将会进入一个全新的海盗主题大逃杀式限时活动,其中包含极高的风险和史诗级的奖励。

《强袭风暴》不是普通的战场,作为一个独立于主游戏之外的活动,玩家可以用大逃杀的风格来体验《魔兽世界》,不分职业、不分装备(除了你在赛局中捡到的),光是技巧和战略的强弱之分就能决定出谁才是能坚持到最后的赢家。本次活动将会开放单人和双人模式,玩家在加入海盗主题的预赛大厅区域前,可以从强袭风暴角色画面新增好友。游玩游戏将可以累计名望轨迹,《巨龙崛起》和《魔兽世界:巫妖王之怒 经典版》的玩家都可以获得奖励。