0

I'm writing my own custom AngularJs validators which look like this:

.directive('float', function ($log) {
    return {
        restrict: 'A',
        require: 'ngModel',
        scope: {float: '='},
        link: function ($scope, ele, attrs, ctrl) {
            var settings = $scope.float || {};

            ctrl.$validators.float = function(value) {
                var valid = isTheInputValidFunction( settings );
                ctrl.$setValidity('float', valid);
                return valid;
            };
        }
    };
});

I'm using the validators like so:

<input type="text"ng-model="someVar" name="preis" float="{precision: 5, scale: 2}">

However, as soon as I attach multiple validators, I get the following error:

Multiple directives [...] asking for new/isolated scope

This is, because all my validators get a settings-object which has to be passed into the scope scope: {float: '='}.

I know that I can use var settings = JSON.parse(attrs.float); in the directives, but it doesn't look right.

So my question is:

How do you correctly implement custom validators in AngularJs?

2 Answers 2

2

It really depends on whether you expect the settings to change.

If you think it will be constant, like in the example you've shown, then simply parsing once the value will be enough. The appropriate service to use in such a case is $parse:

link: function ($scope, ele, attrs, ctrl) {
    var settings = $parse(attrs.float)($scope);

    // …
}

If you think it may be used with a variable, you should watch its content:

link: function ($scope, ele, attrs, ctrl) {
    var settings = undefined;
    $scope.$watch(attrs.float, function (newSettings) {
        settings = newSettings;
    });

    // …
}
Sign up to request clarification or add additional context in comments.

Comments

0

Perhaps it is because you are calling $setValidity. I beleive the whole point of the $validators pipeline was to do it for you. Just return a boolean.

ctrl.$validators.float = function(value) {
  return isTheInputValidFunction( settings );
};

2 Comments

You're right setValidity() is not required, it didn't cause any problems though.
Yes, using $parse() as suggested by @Blackhole solved the problem

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.