需求描述
var str1,str2,str3,str4
- 在textarea里面,不能超过四行
- 最大字符数140
- 输入的字符每35个字符相应赋值给str1,str2,str3,str4,如果大于35截取(保证每个单词的完整性),剩余的字符会拼接在下一行,以此类推
下面是我的code,已经实现,但是看上去有点凌乱,有大神帮忙review修改精简下
define(function (require, exports) {
'use strict';
//@ngInject
exports.customValid = function () {
return {
restrict: 'EA',
replace: 'true',
require: 'ngModel',
link: function (scope, ele, attr, modelCtrl) {
console.log(modelCtrl);
modelCtrl.$parsers.unshift(strProcess)
function strProcess(str) {
var obj = { temp1: '', temp2: '', temp3: '', temp4: '' };
var status = { temp1: false, temp2: false, temp3: false, temp4: false };
if (str) {
var newStr = str.replace(/[\n\r]/g, '< ');
var array = newStr.split(' ');
var temp = '';
array.forEach((item, index, input) => {
if (item && item.length > 35) {
input[index] = item.replace(/(.{35})/g, '$1 ');
}
});
temp = array.join(' ');
var newArray = temp.split(' ');
newArray.forEach((item, index, input) => {
if (!status.temp1 && isVallid(obj.temp1, item)) {
modelCtrl.$setValidity('max', true);
obj.temp1 += item;
if (obj.temp1.charAt(obj.temp1.length - 1) !== '<' && obj.temp1.length < 35) {
obj.temp1 += ' ';
} else {
status.temp1 = true;
}
if (obj.temp1.charAt(obj.temp1.length - 1) === '<') {
status.temp1 = true;
}
} else if (!status.temp2 && isVallid(obj.temp2, item)) {
modelCtrl.$setValidity('max', true);
obj.temp2 += item;
if (obj.temp2.charAt(obj.temp2.length - 1) !== '<' && obj.temp2.length < 35) {
obj.temp2 += ' ';
} else {
status.temp2 = true;
}
if (obj.temp2.charAt(obj.temp2.length - 1) === '<') {
status.temp2 = true;
}
} else if (!status.temp3 && isVallid(obj.temp3, item)) {
modelCtrl.$setValidity('max', true);
obj.temp3 += item;
if (obj.temp3.charAt(obj.temp3.length - 1) !== '<' && obj.temp3.length < 35) {
obj.temp3 += ' ';
} else {
status.temp3 = true;
}
if (obj.temp3.charAt(obj.temp3.length - 1) === '<') {
status.temp3 = true;
}
} else if (!status.temp4 && isVallid(obj.temp4, item)) {
modelCtrl.$setValidity('max', true);
obj.temp4 += item;
if (obj.temp4.charAt(obj.temp4.length - 1) !== '<' && obj.temp4.length < 35) {
obj.temp4 += ' ';
} else {
status.temp4 = true;
}
if (obj.temp4.charAt(obj.temp4.length - 1) === '<') {
status.temp4 = true;
}
} else {
modelCtrl.$setValidity('max', false);
}
});
}
return str;
}
function isVallid(str, appendStr) {
return str.length < 35 && (str.length + appendStr.length <= 35);
}
},
scope: {}
}
}
});