3

I have a directive in which i create many ng-form's and i name each form based on the $index (from the ng-repeat). My problem is that i want to show an error container (that contains the error message) when the form is invalid but i cant find how to properly reference the form.

Here is my code:

<ng-form name="innerForm{{$index}}">

    <label ... ><input name="input" ... />

        <div class="error-container" ng-show="'innerForm'+$index.input.$invalid">
               // show the error message
        </div>

</ng-form>

I want 'innerForm'+$index.input.$invalid to be evaluated as innerForm5.input.$invalid for example.

I have made many attempts but i can't get it to work. What is the correct way to reference my dynamically named form?

2 Answers 2

5

please see here : http://jsbin.com/jocane/4/edit

 <div ng-controller="firstCtrl">
  <div ng-repeat="object in allMyObjects">
    <ng-form name="innerForm{{$index}}">
  <input type="text"  ng-model="object.name" required name="userName">

      <div ng-show="{{'innerForm'+$index}}.userName.$invalid">
               error
        </div>
      </form>

    </div>
Sign up to request clarification or add additional context in comments.

Comments

0

First thing is that, ng-form creates an isolated scope. So if you give a ng-form static name, it will be ok. No need to append $index or anything.

ng-show="innerForm.input.$invalid"

Code snippet to find form controller using element

  var elmParent = $(domEle).parents('form, ng-form, [ng-form]');
    var formCtrl = null;
    var elemCtrl = null;
    if (elmParent.length) {
    var elm = angular.element(domEle);
        formCtrl = elm.scope().$parent[elmParent.attr('name') || elmParent.attr('ng-form')];
    }

Hope this will help

3 Comments

i know it and the reason i do it like that is because i want to reference it externally.
then my friend, you can not do that. For all item ng-form name will be same (without compiled). Though You can access parent ng-form from element scope. Then you can do your validation on that.
Added a code to find ng-from or form form dom element hope it will help

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.