Проверка формы AngularJS. Невозможно прочитать свойство '$ validators' из неопределенного

0

Я хочу создать пользовательскую проверку формы, используя AngularJS. Эта форма должна содержать элементы ввода и выбора. Форма должна быть действительной, если любые впуты пусты или оба заполнены некоторыми значениями. Вот взгляд:

<form name="recipientsForm" novalidate>
    <md-input-container>
        <label>Name</label>
        <input name="name" type="text" ng-model="relationship.name" value="" empty-or-both-filled="relationship.relationshipType">
        <div ng-messages="recipientsForm.name.$error">
            <div ng-message="emptyOrBothFilled">Enter name.</div>
        </div>
    </md-input-container>
    <md-input-container>
        <md-select name="type" placeholder="Select your relation... " ng-model="relationship.relationshipType" empty-or-both-filled="relationship.name">
            <md-option ng-repeat="type in relationshipTypes" value="{{type.relationshipType}}">
                {{type.name}}
            </md-option>
        </md-select>
        <div ng-messages="recipientsForm.type.$error">
            <div ng-message="emptyOrBothFilled">Pick relationship.</div>
        </div>
    </md-input-container>
</form>

И вот директива:

(function () {
    'use strict';

    angular
        .module('app')
        .directive('emptyOrBothFilled', [emptyOrBothFilled]);

    function emptyOrBothFilled() {
        return {
            restrict: 'A',
            required: 'ngModel',
            scope: {
                targetNgModel: '=emptyOrBothFilled'
            },
            link: function($scope, element, attrs, ngModel) {
                ngModel.$validators.emptyOrBothFilled = function(val) {
                    var isValueEmpty = !val;
                    var isTargetEmpty = !$scope.targetNgModel;

                    return (isTargetEmpty && isValueEmpty) || (!isTargetEmpty && !isValueEmpty);
                }

                $scope.$watch('targetNgModel', function() {
                    ngModel.$validate();
                })
            }
        }
    }
})();

Подскажите, пожалуйста, почему я получаю эту ошибку:

TypeError: Cannot read property '$validators' of undefined
    at link (http://localhost:3000/app/shared/directives/EmptyOrBothFilled.js:17:24)
Теги:
angular-material

1 ответ

1
Лучший ответ

Должен быть

require: 'ngModel',

не

required: 'ngModel',

в спецификации спецификации.

  • 0
    Мужик, ты классный, спасибо!

Ещё вопросы

Сообщество Overcoder
Наверх
Меню