Ignas
Ignas

Reputation: 1965

AngularJS - can't access $valid on dynamic inputs

UPDATE: I've added a custom directive which allows me to access the input with a dynamically generated name, but $valid is still undefined.

I'm very new to Angular (trying to switch from jQuery) and I find it pretty awesome, however I've been pulling my hair for hours on this and can't figure out what's causing the issue.

The workflow of the UI that I'm trying to achieve is for a user to click on a step, which then shows an input field, which he has to fill in (validation is required so I'm trying to use ng-required/ng-minlength).

If it passes the validation it should show a tick icon and activate the next step which works the same way.


Now the issue is that I can access the form element, but the object I get is a DOM object and it doesn't include the $valid property, which I need for checking whether the form/field is valid.

17:20 lines are:

console.log($scope.step1); //undefined
console.log(step1); //dom object
console.log(step1.value); //dom object
console.log(step1.value.$valid); //undefined

I've been googling a lot and many questions on SO say that I should be able to access the form through the $scope variable, but unfortunately I can't, though it is accessible via a simple variable name "step1" (dynamically generated form name). I can also access the "value" named field, but it's still just a DOM object so no $valid is available.

JSFiddle: http://jsfiddle.net/Iber/vtvnquee/


My questions are:


Really want to understand Angular because it seems like a proper framework for large apps and the way to go for me.

Upvotes: 3

Views: 1528

Answers (1)

Michael Kang
Michael Kang

Reputation: 52867

Form validation in angular relies on two things:

  1. Your form (or ng-form) element must have a 'name' attribute.

    <form name="myform">
    
  2. Your input (or select) fields must have a 'name' attribute and an ng-model.

    <input type="text" name="name" ng-model="name" />
    

The reason that your form and input fields need a name attribute is because that is how you will find the models on $scope and perform client side validation.

For example

 $scope.myform.name.$error.required
 $scope.myform.name.$valid
 $scope.myform.name.$invalid

[EDIT]

I see that you've already followed these guidelines in your fiddle.

The reason that it does not work is because the name attribute cannot be an interpolated value.

Upvotes: 6

Related Questions