自定义指令不希望在此范围内如何实现?

时间:2016-02-25 07:19:06

标签: angularjs angularjs-directive angularjs-scope

function contentValidator() {
        var _matchContent = {
            require: 'ngModel',
            scope: {
                contentValidator: '='
            },
            link: contentValidatorFn
        };
        return _matchContent;
    function contentValidatorFn(scope, element, attrs, ctrl) {
        scope.$watch(function() {
            var combined;
            if (scope.contentValidator || ctrl.$viewValue) {
               combined = scope.contentValidator + '_' + ctrl.$viewValue; 
            }
            return combined;
        }, function(value) {
            if (value) {
                var origin = scope.contentValidator;
                if (origin !== ctrl.$viewValue) {
                    ctrl.$setValidity("contentValidator", false);
                    return undefined;
                } else {
                    ctrl.$setValidity("contentValidator", true);
                    return ctrl.$viewValue;
                }
            }
        });
    }
}

1 个答案:

答案 0 :(得分:1)

我建议您使用$validators管道来设置表单字段的有效性。

ngModel.$validators.contentValidator = function(modelValue, viewValue) {
    var value = modelValue || viewValue;
    return condition ? value : undefined; //condition would be what you wanted to check
};

基本上,当您从$validators contentValidator函数返回定义的值时,但是当您不返回angular时,将在该字段上添加content-validator类&相同的属性会添加到该表单字段,如myForm.formFields.$error.contentValidator = true