[英]AngularJS - How to validate an element directive?
我已经创建了一个数字指令
function numberInputDirective()
{
return
{
restrict: 'E',
scope:
{
model: '=',
disabled: '=?',
decimals: '=?',
form: '=',
name: '='
},
require: '^form',
replace: true,
templateUrl: 'directives/pxNumberInput.html',
link: function (scope, element, attrs, form)
{
scope.inError = function ()
{
return form.control.$valid; //I need to do something like this
}
}
}
我需要检查isError函数中控件中的值是否有效
模板是:
<input class="input-field form-control" type="number" ng-model="model">
HTML是:
<form role="form" class="form-horizontal psi-keyrates-yieldform psi-keyrates-historical-topcurves" name="SampleControlsForm" novalidate>
<px-number-input id="objectiveid" name="numericExample" model="sampleDataModel.numericField" placeholder="Enter numeric value" label="Numeric" required maxlength="10"></px-number-input>
</form>
尽管form变量告诉我表单(form。$ valid)是否有效,但我需要知道在提交表单时此特定指令是否具有有效值。 像这样的form.control。$ valid。
我不知道此指令中控件的名称,因为它将在html中设置。
我试过了:var elem = ctrl。$ name +'。' + element.attr('名称')+'。$ valid'; 这将返回字符串“ SampleControlsForm.numericExample。$ valid”,如果我在上面添加了监视,它将无济于事,scope。$ eval也无济于事。
我确定我没有正确使用它。
这是显示自定义数字验证器的示例:
require
ngModel以便可以访问其控制器。 $validators
对象(角度1.3及更高版本)添加属性来添加自己的自定义验证器。 对于angular <1.3,请使用ngModelController.$setValidity
$error
对象上设置$watch
以插入/删除图像,具体取决于验证是通过还是失败。 ngModel
一起使用的自定义指令,而无需定义模板。 $validators
对象允许您为同一ngModel
注册多个验证指令。 要添加验证器,只需将验证指令添加到与ngModel
相同的元素中。
var app = angular.module('app', []); app.directive('myNumber', function() { return { restrict: 'A', require: 'ngModel', compile: function(element, attr) { var img = angular.element('<img src="https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcTTyptDmp09eMq1nHtcJHVTAMkKgqdi1ZiGMQSjFeYNApkO92zhCA" />'); return function(scope, element, attr, ngModelCtrl) { function isNumber(n) { return !isNaN(parseFloat(n)) && isFinite(n); } ngModelCtrl.$validators.mynumber = function(val) { return isNumber(val); }; scope.$watch(function() { return ngModelCtrl.$error.mynumber; }, function(newVal) { if (newVal) { element.after(img); } else { img.remove(); } }); } } } });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script> <div ng-app="app"> <form name="form"> <input type="text" name="age" my-number ng-model="age" /> {{ age }} </form> {{ form.age.$error }} </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.