[英]How can I convert this function into Angular directive
How can I convert this function into an AngularJS
directive? 如何将该函数转换为
AngularJS
指令? I want to make it validate user input in real time. 我想让它实时验证用户输入。 But even when I'm trying to use it as regular function in controller I'm getting an error:
但是,即使我试图将其用作控制器中的常规函数,也会出现错误:
"Error: pesel.substring is not a function"
“错误:pesel.substring不是函数”
function decode(pesel)
{
var year=parseInt(pesel.substring(0,2),10);
var month = parseInt(pesel.substring(2,4),10)-1;
var day = parseInt(pesel.substring(4,6),10);
if(month>80) {
year = year + 1800;
month = month - 80;
}
else if(month > 60) {
year = year + 2200;
month = month - 60;
}
else if (month > 40) {
year = year + 2100;
month = month - 40;
}
else if (month > 20) {
year = year + 2000;
month = month - 20;
}
else {
year += 1900;
}
var birthday=new Date();
birthday.setFullYear(year, month, day);
var weights = [9,7,3,1,9,7,3,1,9,7];
var sum = 0
for(var i=0;i<weights.length;i++) {
sum+=(parseInt(pesel.substring(i,i+1),10) * weights[i]);
}
sum=sum % 10;
var valid=(sum===parseInt(pesel.substring(10,11),10));
//sex
if(parseInt(pesel.substring(9,10),10) % 2 === 1) {
var sex='m';
} else {
var sex='f';
}
return {valid:valid,sex:sex,date:birthday};
}
As Abdo stated above the value you are passing to your function, pesel
, probably isn't a string. 正如Abdo在上面所述,您要传递给函数
pesel
的值可能不是字符串。
The first line in your function should be: 函数的第一行应为:
pesel = (pesel || '').toString();
This line makes sure you don't stringify falsey variables and will make sure pesel
is in fact a string. 此行确保您不对假变量进行字符串化,并确保
pesel
实际上是字符串。
If you want to validate some input, consider as a better option to create a parser/formatter pair or a validator for that purpose. 如果要验证某些输入,请考虑为此目的创建一个解析器/格式化程序对或验证器,这是一个更好的选择。
Use formatter/parsers for retrieving birthday and sex values, and a validator to check the value. 使用格式化程序/解析器来检索生日和性别值,并使用验证器来检查该值。
Best 最好
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.