Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

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?

share|improve this question
up vote 4 down vote accepted

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>
share|improve this answer
    
You are the man! Thanks it works just fine :) – Christos Baziotis Jul 25 '14 at 11:48
    
@agnostos you're welcome :) – sylwester Jul 25 '14 at 11:48
    
Exactly what I was looking for !! – Shankar Regmi Jul 6 '15 at 6:11

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

share|improve this answer
    
i know it and the reason i do it like that is because i want to reference it externally. – Christos Baziotis Jul 25 '14 at 11:26
    
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. – dhavalcengg Jul 25 '14 at 11:35
    
Added a code to find ng-from or form form dom element hope it will help – dhavalcengg Jul 25 '14 at 11:40

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.