maja
maja

Reputation: 18034

Custom validators with AngularJs

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?

Upvotes: 0

Views: 113

Answers (2)

SoEzPz
SoEzPz

Reputation: 15912

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

Upvotes: 0

Blackhole
Blackhole

Reputation: 20401

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

    // …
}

Upvotes: 2

Related Questions