0

I have a directive barFoo that has the following template:

<div>
    ....
    <input ng-model="data">
</div>

This directive is used inside a form! Now, inside this directive I want to do things like

element.find('input').$setValidity('bar-valid', false);

However, this doesn't work. Also the input field doesn't have a name attribute. Is there any way to do this without a 'name' attribute ?

UPDATE: An other solution is to define ngModel on the directive element

<bar-foo ng-model="data.value"></bar-foo>

And rewrite the directive as follows

....
    .directive('barFoo', function () {
        return {
            require: 'ngModel',
            ...
            link: function (scope, element, attrs, ctrl) {
                ctrl.$setValidity('bar-valid', false);
            }
    });

2 Answers 2

1

Have a look at this question: AngularJS Form Validation Directive $setValidity on element

I will give you exactly what you need including code

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

4 Comments

The solution in that post is to use the name attribute. In this question I'm wondering if it is possible to do it without
$serValidity is part of the angularjs magic. If you want to use it, than you need to stick to angularjs Form handling. And this means, you need a name attribute. What is the problem with the name attribute anyway?
Well, the directive is generic. Inside one form it can be used multiple times. So if I need to use the name attribute I need to generate a random name (I think). So thats why I was wondering if I could do without
you will still have to user the name attribute.. only thing is: you will have to use ng-form inside your directive
1

You can call a directive with name="itAmazingName" and use it in directive template, that should solve your problems

3 Comments

This cannot work. If you have multiple elements with name="itAmazingName", I would say that the $setValidity breaks, because the form treats all the elements as one entity!
Who said about multiple elements with same name? I only suggested to use name for directive and then consume it in directive template
Ok, you want to call the directive element with a name attribute. Interesting, but still you have to generate a name attribute value.

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.