在ng的实际开发中,我们会遇到很多变态的需求(哈哈),这里主要是讲解一下怎么格式化input输入框的值:
1、HTML结构
<input input-uppercase ng-model="test" type="text" class="form-control">
2、编写指令
var app = angular.module('myApp',[]); app.directive("inputUppercase",function (debounce) {//注入写好的服务 return { require: "ngModel", restrict: "A", link: function (scope, elem, attrs, modelCtrl) { elem.on("keyup", debounce.debounce(function (event) { scope.$apply(function () {//scoep.$apply()这个函数是为了更新input中model的值 if (!angular.isUndefined(modelCtrl.$modelValue) && /[a-z]/.test(modelCtrl.$modelValue)) { modelCtrl.$setViewValue(angular.uppercase(modelCtrl.$modelValue)); elem.val(modelCtrl.$modelValue); console.log(modelCtrl.$viewValue)//主要是输入英文字母,自动转成大写 } }); }, 50)) } } })
3、上面的指令中,利用JS库lodash.js,封装了一个延时的服务,这个服务主要是为了间隔多少秒执行一次脏检查,不然太耗性能了,就像我们用$scope.$watch()来监控某一个ngModel,如果不做延时处理,在大代码量的情况下,会很可怕的。
app.service('debounce',function(){ //这个是延时执行检查 this.debounce = function (fun, wait) { if (angular.isUndefined(wait)){ wait = 800; } return _.debounce(fun, wait);//lodash.js插件 } })
4、简单讲解一下ngModel的属性,具体的自己去捣腾吧
$parsers 属性,保存了从viewValue向modelValue绑定过程中的处理函数,它们将来会依次执行
$viewValue视图的值
$modelValue模型里的值
$formatters 属性,保存的是从modelValue向viewValue绑定过程中的处理函数
$setViewValue属性,当view发生了某件事情时,从view向model绑定调用,把viewValue保存选来