Eduardo
Eduardo

Reputation: 113

Check the validity of dynamically added forms on angularjs controller's $scope

To check the validity of a form in my page, I test this property in my controller's scope:

$scope.formName.$valid

The problem is that when I add forms dynamically to the page (based on a model property), the $scope.newFormName property is not added to the scope.

This plnkr illustrate the problem

  1. Click the 'Add form' button to add forms to the page
  2. Click the 'Search forms' to update the list with the forms found in the $scope
  3. Note that the added forms are not found in the scope

Is there any way to make this work? How can I check the validity of this dynamically added forms?

Upvotes: 4

Views: 1305

Answers (2)

Matthias
Matthias

Reputation: 15415

So your code adds a list of identical forms. And you want to see whether this list is valid or not.

The solution is to use ngForms within a parent form. See this Plunkr (my modified version of yours).

  • Form input values are bound to objects in the $scope.dynamicData array, which also is used by ngRepeat to create the list of forms.
  • Invalid fields are shown with a solid red border, and invalid forms have a dashed red border.

When forms are nested like this, the parent form is invalid when any of its child forms are invalid.

Upvotes: 2

Ronnie
Ronnie

Reputation: 11198

I'd use angular.element(). I would also personally get it via ID rather than name, but that is just me. View this plunker to see what I did: http://plnkr.co/edit/b87HJt

I'm using angular.element() to get the element by the name, getElementsByName and then using the $attr directive to get at the name.

Upvotes: 0

Related Questions