我正在使用自定义角度表单验证来验证基于具有值的字段和下拉列表的选定值的字段。我在页面上使用了相同的代码部分(因此也使用了相同的指令)两次。所以我可以重复使用,我尝试向指令发送一个参数。这一切都很好。但是,当创建子范围时,它会将我的 2 向绑定中断回fruit.cost
.
我究竟做错了什么?我希望所有验证都能正常工作,但也保留 2 向绑定。这是我的小提琴代码的副本:
JS
function MainCtrl($scope){
$scope.localFruits = [
{name: 'banana'},
{name: 'orange'},
{name: 'grape'}
];
$scope.fruits = [
{name: 'banana'},
{name: 'orange'},
{name: 'grape'}
];
$scope.costRequired = [
'local',
'overseas'
];
$scope.selectedCostRequired = '';
}
angular.module('test', []).directive('customRequired', function() {
return {
restrict: 'A',
require: 'ngModel',
scope: {
requiredWhenKey: '=',
cost: '=' // I think the problem is here?? Can't figure out how to pass the property I want to bind to
},
link: function(scope, elem, attrs, ctrl) {
//console.log(scope);
function isValid(value) {
if (scope.$parent.selectedCostRequired === scope.requiredWhenKey) {
return !!value;
}
return true;
}
ctrl.$parsers.unshift(function(value) {
var valid = isValid(value);
scope.$parent.subForm.cost.$setValidity('customRequired', valid);
return valid ? value : undefined;
});
ctrl.$formatters.unshift(function(value) {
scope.$parent.subForm.cost.$setValidity('customRequired', isValid(value));
return value;
});
scope.$watch('$parent.$parent.selectedCostRequired', function() {
scope.$parent.subForm.cost.$setValidity('customRequired', isValid(ctrl.$modelValue));
});
}
};
});
HTML
<div ng-app="test" ng-controller="MainCtrl">
<form name="form">
Which grouping is required? <select name="costRequired" ng-model="selectedCostRequired" ng-options="t for t in costRequired"></select>
<h2>Local</h2>
<div ng-repeat="fruit in localFruits" ng-form="subForm">
{{fruit.name}}: <input name="cost" ng-model="fruit.cost" required-when-key="'local'" custom-required/> bound value is: [{{fruit.cost}}]
<span class="error" ng-show="subForm.cost.$error.customRequired">Required</span>
</div>
<h2>Overseas</h2>
<div ng-repeat="fruit in fruits" ng-form="subForm">
{{fruit.name}}: <input name="cost" ng-model="fruit.cost" required-when-key="'overseas'" custom-required/> bound value is: [{{fruit.cost}}]
<span class="error" ng-show="subForm.cost.$error.customRequired">Required</span>
</div>
<div ng-show="form.$invalid" class="error">some form error(s) still exist</div>
<div ng-show="!form.$invalid" class="okay">form looks good!</div>
</form>
</div>