AngularJS输入监视$ valid或$ error [英] AngularJS input watch $valid or $error
问题描述
我正在尝试$watch
控件的$error
或$valid
值.这是控件:
I'm trying to $watch
the $error
or the $valid
value of a control. This is the control:
<form id="myForm" name="myForm">
<input name="myInput" ng-model="myInputMdl" business-validation/>
</form>
business-validation
是一个自定义指令,可更改控件的有效性.我已经根据在
business-validation
is a custom directive that alters the validity of the control. I've attempted the following approaches (using either $valid
or $error
) based on what I've read at AngularJS directive watch validity:
-
这不起作用,因为
$valid
在myForm.myInput
上不存在.
$scope.$watch('myForm.myInput.$valid', function (isValid) {
$scope.usefulVariable = step3.CreditCardNumber.$valid;
},true);
此功能不起作用,因为显然无法观看validity.valid
.
$scope.$watch('myForm.myInput.validity.valid', function (isValid) {
$scope.usefulVariable = step3.CreditCardNumber.$valid;
},true);
这不起作用,因为每次更改都不会监视$scope.myInputMdl
.
$scope.$watch('$scope.myInputMdl', function (isValid) {
$scope.usefulVariable = step3.CreditCardNumber.$valid;
},true);
不能从控制器监视有效性吗?
Can't the validity be watched from a controller?
编辑
我不是要编写或编辑business-validation
指令.我正在尝试的是从窗体的控制器$watch
$valid
或$error
.
I'm not trying to write or edit business-validation
directive. What I'm trying is to $watch
$valid
or $error
from form's controller.
编辑2
控制器的代码是:
app.controller('WizardBusinessActionCtrl',
function ($scope, $http, $parse, $filter, wizardBusinessActionService, $timeout) {
//controller code
}
);
推荐答案
我看不出您的第一个变体不起作用的任何原因.
I don't see any reason why your first variant shouldn't work.
HTML:
<div ng-app="myApp">
<div data-ng-controller="MainController">
<form name="myForm">
<input name="myInput" ng-model="myInputMdl" business-validation />
</form>
</div>
</div>
控制器和指令:
var myApp = angular.module('myApp', []);
myApp.controller('MainController', function ($scope) {
$scope.$watch('myForm.myInput.$valid', function (validity) {
console.log('valid', validity);
});
});
myApp.directive('businessValidation', function () {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, elem, attr, ctrl) {
function validate (input) {
return input === 'hello';
}
ctrl.$parsers.unshift(function (value) {
var valid = validate(value);
ctrl.$setValidity('businessValidation', valid);
return valid ? value : undefined;
});
ctrl.$formatters.unshift(function (value) {
ctrl.$setValidity('businessValidation', validate(value));
return value;
});
}
};
});
$valid
属性值将在myInput
有效性更改时更改,并且将触发$watch
回调.
$valid
property value will change when myInput
validity changes, and $watch
callback will be fired.
请参阅示例: http://jsfiddle.net/Lzgts/287/
这篇关于AngularJS输入监视$ valid或$ error的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!