简体   繁体   English

带有ngModel的Angularjs指令

[英]Angularjs Directive with ngModel

I've got a javascript function that we use in a legacy system that alters the format of an input field as you type; 我有一个javascript函数供我们在旧版系统中使用,该函数会在您键入内容时更改输入字段的格式;

function checkValidDate(dateStr) {
    if (dateStr && dateStr != '') {
        dateStr = dateStr.replace('/', '');
        dateStr = dateStr.replace('/', '');
        var d_f_m = dateStr;
        var d_f_d = dateStr;
        var d_f_y = dateStr;
        var err_msg = '';
        var d_s_day = d_f_d.slice(0, 2);
        d_s_day = d_s_day + "/";
        var d_s_month = d_f_m.slice(2, 4);
        d_s_month = d_s_month + "/";
        var d_s_year = d_f_y.slice(4, 8);
        //Now we check the year to see if it is only 2 digis, if is, add 2 more
        if (d_s_year.length == 2) {
            d_s_year = '19' + d_s_year;
        }
        return d_s_day + d_s_month + d_s_year;
    } else {
        return null;
    }
}

I've been trying to convert this function to an angularjs directive using ngModel but I just can't seem to sort it out. 我一直在尝试使用ngModel将此函数转换为angularjs指令,但似乎无法对其进行整理。 Would anyone know how to convert this to an angular directive? 有人知道如何将其转换为角度指令吗?

Many thanks! 非常感谢!

There are a billion ways to do what you want. 有十亿种方法可以做您想要的。 Here is a quick solution I threw together to get your started: 这是我快速入门的快速解决方案:

JS: JS:

var app = angular.module('myApp', []);

app.directive('dateValidator', function() {
  return function(scope, element, attrs) {
    // Watch for changes to the date model
    scope.$watch('date', function(newVal, oldVal) {      
      if (!angular.equals(newVal, oldVal)) {
        var formattedDate = checkValidDate(newVal);
        if (formattedDate) {
          element.text(formattedDate);
        }
      }
    });
  });
});

HTML: HTML:

<input type="text" date-validator date="myDate" ng-model="myDate" />

I recommend that you write a custom angular validator. 我建议您编写一个自定义角度验证器。 There are some good articles on it. 有一些不错的文章。 Here is one that I like: 这是我喜欢的一个:

Form Validation with AngularJS 使用AngularJS进行表单验证

The form and its containing fields have special properties appended to them that you can leverage for binding expressions and client-side validation: 表单及其包含字段具有附加的特殊属性,您可以利用它们来绑定表达式和客户端验证:

$pristine, $dirty, $valid, $error $原始,$脏,$有效,$错误

Not sure if you wanted it validated as you type or after you leave a field. 不知道是要在输入时还是在离开字段后对其进行验证。 Either can work, though the below is implemented to validate after you leave the field (lose focus). 尽管您可以在离开该字段后进行以下验证(失去重点),但无论哪种方法都可以。

The existing algorithm was used, though it looks like it handles only very specific cases (ie 2 digit day, 2 digit month, 2-4 digit year) and could be improved. 使用了现有算法,尽管看起来它只能处理非常特殊的情况(即2位数字的日子,2位数字的月份,2-4位数字的年份),并且可以改进。 For the moment, it was copied as is. 目前,它是按原样复制的。 JSFiddle is here http://jsfiddle.net/pSh4R/18/ JSFiddle在这里http://jsfiddle.net/pSh4R/18/

HTML: HTML:

<div ng-app='app'>
    Please enter a date
    <br/>
    <input type='text' dateformat ng-model='myDate'></input>
    (Hit TAB when done)
    <hr/>
    Model Value : {{myDate}}
</div>

Directive Declaration: 指令声明:

var app = angular.module('app',[]);

app.directive('dateformat', function(){
    return {
        restrict : 'A',
        scope : {
            dateStr : '=ngModel'
        },
        link : function(scope, element){

            element.bind('focusout', function (){                 
                scope.$apply(function(){
                    scope.dateStr = checkValidDate(scope.dateStr);
                });
            });

            function checkValidDate(dateStr) {
                if (dateStr && dateStr != '') {
                    dateStr = dateStr.replace('/', '');
                    dateStr = dateStr.replace('/', '');
                    var d_f_m = dateStr;
                    var d_f_d = dateStr;
                    var d_f_y = dateStr;
                    var err_msg = '';
                    var d_s_day = d_f_d.slice(0, 2);
                    d_s_day = d_s_day + "/";
                    var d_s_month = d_f_m.slice(2, 4);
                    d_s_month = d_s_month + "/";
                    var d_s_year = d_f_y.slice(4, 8);
                    //Now we check the year to see if it is only 2 digis, if is, add 2 more
                    if (d_s_year.length == 2) {
                        d_s_year = '19' + d_s_year;
                    }
                    return d_s_day + d_s_month + d_s_year;
                } else {
                    return null;
                }
            }   
        }
    };
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM