且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何判断角形自定义指令无效

更新时间:2023-11-11 08:04:28

您可以使用ngModel验证器:

.directive("smth", function($rootScope) {
    var link = function(scope, element, attrs, ngModelCtrl) {

        // Add custom validator
        ngModelCtrl.$validators["timeString"] = function(modelValue) {
            return !$rootScope.timeStringValid(modelValue);
        }
    };
    return {
        restrict: "E",
        scope: {
            name: "=name",
            label: "=label",
            ngModel: "=",
            required: "=required"
        },
        // require ngModel controller
        require: "ngModel",
        link: link,
        templateUrl: "smth.html"
    };
});

这样,角度将包含对其$invalid属性和$errors(myForm.myFieldName.$errors.timeString)的验证错误

This way angular will include the validation errors to its $invalid property and the $errors (myForm.myFieldName.$errors.timeString)