pirata000
pirata000

Reputation: 128

validation of a form added with a directive

I would like to access the content of the validation variables provided from AngularJS for the forms. I need to add forms using a directive like in the code, but if I do that I can't access the $dirty,$error,$invalid variables anymore and I need to access them.

JS:

myApp.directive('test', function() {
  return {
    scope : {
      nameform: "=",
      nameinput: "=",
      type: "="
    },
    template: '<form name=nameform></form>',
    restrict: 'E',
    compile: function (elem,attr){
      var form = elem.find("form");
      if(attr.type == "text")
        form.html('<input type="text" name="nameinput" ng-model="data.text" placeholder="type here..." required />');

    }
  };
});

HTML:

<test nameform="valform" nameinput="valinput" type="text"/>
{{valform.valinput.$invalid}}

Upvotes: 0

Views: 252

Answers (3)

Michael Kang
Michael Kang

Reputation: 52847

When you build your HTML for your input controls, make sure you append the name attribute correctly based on 'nameinput' passed in as an attribute:

myApp.directive('test', function() {
   return {
      scope : {
         nameform: "=",
         nameinput: "=",
         type: "="
      },
      template: '<form name=nameform></form>',
      restrict: 'E',
      compile: function (elem,attr){
           var form = elem.find("form");
           if(attr.type == "text")
                form.html('<input type="text" name="' + attr.nameinput +'" ng-model="data.text" placeholder="type here..." required />');

      }
   };
});

Upvotes: 0

Craig Squire
Craig Squire

Reputation: 2141

Change your directive to be ng-form instead of form (because ng-form is nestable). Then wrap your directive inside another form element and give that new form element a name. The outer form element will bind to your outer scope and you can access the properties that way.

Directive template:

"<ng-form name="valform"></ng-form>"

HTML:

  <body ng-view>
    <div>Valid: {{outerform.$valid}}</div>
    <div>Errors: {{outerform.$error}}</div>
    <form id="outerform" name="outerform">
    <test type="text"/>
    </form>
  </body>

Side note, form names don't play nice with dynamic names. The plunkr below uses static names so I could help you with your current problem. I found a solution to the dynamic name problem on a different SO post...I think this one... Dynamic validation and name in a form with AngularJS

Here's a plnkr with your working form... http://plnkr.co/edit/RFrRXp2kWkP1Mefwl3Kn?p=preview

Upvotes: 0

jvrdelafuente
jvrdelafuente

Reputation: 2002

I think that you can't. Because you are using isolated scope for building your directive, so you don't have acces to the information. You can try to build you directive using share scope, and I think that you would be able to access this information.

Upvotes: 1

Related Questions