AngularJS表单自定义验证。无法阅读财产' $ validators'未定义的

时间:2015-07-03 04:43:20

标签: javascript angularjs angular-material

我想使用AngularJS创建自定义表单验证。该表单应该有输入和选择元素。当imputs为空或者两者都填充了某些值时,表单应该是有效的。以下是观点:

<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)

1 个答案:

答案 0 :(得分:1)

应该是

require: 'ngModel',

不是

required: 'ngModel',

在指令规范中。