我已经为表单控件创建了指令。 对于required,如果值为空,则验证工作正常但我想在emptyDirective.js中设置为空和“-1”所以修改了selectControlDir。 但是没有定义错误ctrl。
选择控制指令代码
function selectControlDir()
{
return {
transclude: true,
restrict: 'E',
scope: {
ngModel: '=',
queObj: '='
},
template: '<div class="form-group">\n\
<label for="{{queObj._attributeName}}" class="col-sm-5 control-label">{{queObj._text}}</label>\n\
<div class="col-sm-6"><select {{queObj._attributeName}} ng-options="ans._value as ans._promptText for ans in queObj._answerOptions" ng-model="ngModel" ng-required="queObj._required" class="form-control {{queObj._pageAttributes.cssclass}}" name="{{queObj._attributeName}}" id="{{queObj._attributeName}}"></select>\n\
</div>'
,
link: function (scope, element, attrs)
{
if(angular.isUndefined(scope.ngModel))
{
scope.ngModel = scope.queObj._pageAttributes.defaultValue;
}
// add a parser that will process each time the value is
// parsed into the model when the user updates it.
ctrl.$parsers.unshift(function (value) {
if (value) {
// test and set the validity after update.
var valid = value.charAt(0) == '' || value.charAt(0) == '-1';
ctrl.$setValidity('required', valid);
}
// if it's valid, return the value to the model,
// otherwise return undefined.
return valid ? value : undefined;
});
}
};
}
我在这里缺少什么? 有关完整代码https://plnkr.co/edit/GA74YHNFxFb0ARg16Sjj?p=preview
,请参阅plunker如果我删除了此ctrl.$parsers.unshift
代码,则会出现错误。
答案 0 :(得分:1)
ctrl未定义,因为您错过了在指令中设置require属性:
return {
transclude: true,
restrict: 'E',
require: 'ngModel',
scope: {
ngModel: '=',
queObj: '='
},
template: '...'
,
link: function (scope, element, attrs, ctrl)
{
if(angular.isUndefined(scope.ngModel))
{
scope.ngModel = scope.queObj._pageAttributes.defaultValue;
}
// add a parser that will process each time the value is
// parsed into the model when the user updates it.
ctrl.$validators.required = (function (value) {
var valueToTest = value || '';
// if it's valid, return the value to the model,
// otherwise return undefined.
return !(valueToTest.charAt(0) == '' || valueToTest.charAt(0) == '-1');
});
}
}
在定义了require属性后,您可以访问链接功能中的ctrl
编辑:通过这种方式,双向绑定(ngModel:&#39; =&#39;)是不必要的