【发布时间】:2015-03-08 18:57:33
【问题描述】:
我有一个链接到表单上的文本框的指令,我希望该指令设置“必需”错误。
这是一个显示我正在尝试做的小提琴
http://jsfiddle.net/scottieslg/7qLsj3rr/3/
HTML:
<div ng-app='myApp' ng-controller='TestCtrl'>
<ng-form name='testForm'>
<input type='text' name='myInput' />
<div ng-messages="testForm.myInput.$error">
<div ng-message="required">Required</div>
</div>
<test-directive ng-model='testModel'></test-directive>
</ng-form>
</div>
Javascript:
var app = angular.module('myApp', ['ngMessages']);
app.controller('TestCtrl', function($scope) {
$scope.testModel = {}
});
app.directive('testDirective', function() {
return {
restrict: 'E',
require: 'ngModel',
template: '<div><button ng-click="setError()">Set Error</button></div>',
link: function(scope, element, attrs, ngModelCtrl) {
scope.setError = function() {
// How can I set .setValidate('require', true) on myInput from here??
}
}
}
});
【问题讨论】:
-
为什么在
testDirective上需要ng-model? -
从你的问题中不清楚你想做什么,请更新你的问题
-
当字段有值时,你不能假装
required验证器应该失败。我认为您可能有兴趣创建您的custom validation logic。
标签: angularjs validation angularjs-directive