Ephi Gabay
Ephi Gabay

Reputation: 938

AngularJS form validation while adding dynamic elements

I have a form with AngularJS validation.
The problem is that I add input elements to this form using Jquery and AngularJS doesn't add those elements into the form's validation..
Here's an example: http://jsfiddle.net/ULEsy/

var input = $compile($('<input type="text" ng-model="textinput" required />'))($scope);
$("#someform").append(input);

In the example, even though the input field is not valid (empty - can be seen by the red border), the entire form is valid. Any help?

Upvotes: 4

Views: 1014

Answers (1)

Yaron Schwimmer
Yaron Schwimmer

Reputation: 5357

@Ephi and I found a solution for this problem. Apparently, you need to first append the element to the DOM, and only then use $compile. Also, the new element needs a name.

See here

angular.module("app", []).controller('someController', function($scope, $compile) {   
    $scope.add = function() {
        var input = $('<input type="text" ng-model="textinput" name="x" required />');
        $("#someform4").append(input);    
        $compile(input)($scope);
    }
});

Upvotes: 2

Related Questions