在最原始的 Angular 应用程序中,我试图为输入字段创建一个指令,它会更改父级的 ng-model 值。
HTML:
<form novalidate>
<input ng-model="ctrl.myvalue" mydirective minlength="19" />
{{ ctrl.myvalue }}
</form>
JS:
var app = angular.module('app', []);
app.directive('mydirective', function(){
return {
scope: { ngModel: '=' },
link: function(scope, el) {
el.on('input', function(e) {
this.value = this.value.replace(/ /g,'');
scope.ngModel = this.value;
})
}
}
})
app.controller('MyController', function(){
this.myvalue = '';
})
问题是,如果我将此指令与 minlength
或 pattern
一起用于输入验证,它会出现特定行为:您在输入中输入的第二个字母会消失; ng-model
也得到 undefined
值。未经验证,代码可以完美运行。
我也尝试创建一个自定义验证作为解决方法,但它具有相同的效果。
您能解释一下或提出前进的方向吗?
最佳答案
您可以使用 unsift,也可以使用 render 进行第一次迭代。
通常你可以使用 ctrl.$setViewValue
但你可以确定当值不改变时不会重新启动......
var testModule = angular.module('myModule', []);
testModule.controller('testCntrl', ['$scope', function ($scope) {
$scope.test = 'sdfsd fsdf sdfsd sdf';
}]);
testModule.directive('cleanSpaces', [function () {
return {
require: '?ngModel',
link: function (scope, $elem, attrs, ctrl) {
if (!ctrl) return;
var filterSpaces = function (str) {
return str.replace(/ /g, '');
}
ctrl.$parsers.unshift(function (viewValue) {
var elem = $elem[0],
pos = elem.selectionStart,
value = '';
if (pos !== viewValue.length) {
var valueInit = filterSpaces(
viewValue.substring(0, elem.selectionStart));
pos = valueInit.length;
}
//I launch the regular expression,
// maybe you prefer parse the rest
// of the substring and concat.
value = filterSpaces(viewValue);
$elem.val(value);
elem.setSelectionRange(pos, pos);
ctrl.$setViewValue(value);
return value;
});
ctrl.$render = function () {
if (ctrl.$viewValue) {
ctrl.$setViewValue(filterSpaces(ctrl.$viewValue));
}
};
}
};
}]);
http://jsfiddle.net/luarmr/m4dmz0tn/
更新 我用最后的代码更新了 fiddle ,并用 Angular 验证示例更新了 html,并用 ng-trim ( ngModel.$parsers ingore whitespace at the end of ng-model value ) 更新了 html。
关于javascript - Angularjs 在具有验证的同一元素的指令中更改 ng-model,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31941747/