我正在使用ng-pattern来验证某些表单字段,并且我正在使用ng-change来监视和处理任何更改,但是ng-change(或$ scope.$ watch)只会在表单元素位于$有效状态!我是棱角分明的,所以我不知道如何解决这个问题,虽然我怀疑新的指令是要走的路.
如何在$ invalid和$ valid表单元素状态下触发ng-change,ng-pattern仍然像以前一样设置表单元素状态?
HTML:
<div ng-app="test">
<div ng-controller="controller">
<form name="form">
<input type="text" name="textbox" ng-pattern="/^[0-9]+$/" ng-change="change()" ng-model="inputtext"> Changes: {{ changes }}
</form>
<br>
Type in any amount of numbers, and changes should increment.
<br><br>
Now enter anything that isn't a number, and changes will stop incrementing. When the form is in the $invalid state, ng-change doesn't fire.
<br><br>
Now remove all characters that aren't numbers. It will increment like normal again. When the form is in the $valid state, ng-change will fire.
<br><br>
I would like ng-change to fire even when the the form is $invalid.
<br><br>
form.$valid: <font color="red">{{ form.$valid }}</font>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
使用Javascript:
angular.module('test', []).controller('controller', function ($scope) {
$scope.changes = 0;
$scope.change = function () {
$scope.changes += 1;
};
});
Run Code Online (Sandbox Code Playgroud)
我创建了一个工作的JS Fiddle,它显示了我遇到的问题.
顺便说一句,这个角度问题似乎也是相关的:https: //github.com/angular/angular.js/issues/1296
Eug*_*ene 71
您可以使用ng-model-options更改输入的行为.
只需将此属性添加到您的输入中,ng-change事件将触发:
ng-model-options="{allowInvalid: true}"
Run Code Online (Sandbox Code Playgroud)
请参阅:https://docs.angularjs.org/api/ng/directive/ngModelOptions
小智 15
你只需要添加
ng-model-options="{ updateOn: 'default' , allowInvalid:'true'}"
Run Code Online (Sandbox Code Playgroud)
这表示可以使用未正确验证的值而不是默认行为来设置模型.
编辑当ng-model-options没有时,答案已得到解答.请参阅最高投票的答案.
你可以编写一个简单的指令来监听input事件.
HTML:
<input type="text" name="textbox" ng-pattern="/^[0-9]+$/" watch-change="change()" ng-model="inputtext"> Changes: {{ changes }}
Run Code Online (Sandbox Code Playgroud)
JS:
app.directive('watchChange', function() {
return {
scope: {
onchange: '&watchChange'
},
link: function(scope, element, attrs) {
element.on('input', function() {
scope.$apply(function () {
scope.onchange();
});
});
}
};
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
22001 次 |
| 最近记录: |