我创建自定义指令来检查输入的值,如果它与家庭成员的总数不同,则显示错误消息以提醒用户注意他输入了错误的值。
app.directive('exact',
function () {
var link = function ($scope, $element, $attrs, ctrl) {
var validate = function (viewValue) {
var comparisonModel = $attrs.exact;
if (!viewValue || !comparisonModel) {
// It's valid because we have nothing to compare against
ctrl.$setValidity('exact', true);
}
if (parseInt(viewValue) != parseInt(comparisonModel)) {
ctrl.$setValidity('exact', false);
return viewValue;
} else {
ctrl.$setValidity('exact', true);
return viewValue;
}
};
ctrl.$parsers.unshift(validate);
ctrl.$formatters.push(validate);
$attrs.$observe('exact', function (comparisonModel) {
return validate(ctrl.$viewValue);
});
};
return {
require: 'ngModel',
link: link
};
}
);
如果输入不等于 {{total}} 值,这应该将输入的有效性设置为 false
<md-input-container class="md-block">
<input required type="number" exact="{{total}}"name="num" ng-model="house.No" style="max-width:100px;">
<div ng-messages="Form.num.$error" multiple>
<div ng-message="required">Please provide Total Household Members.</div>
<div ng-message="exact">According to your input in step 1 and step 3(part B), your total Household Members is {{total}} </div>
</div>
</md-input-container>