Aleksandrus
Aleksandrus

Reputation: 1754

AngularJS - How to compile inputs inside form?

I have a form declared in the html file. The inputs are generated dynamically.

That means, they are built as strings in javascript and then compiled inside a custom directive in angular.

app.directive('customInput', function($compile){
return{
  restrict: 'E',
  scope: true,
  link: function(scope, element, attrs){
    var html = "<input type='text' ng-model='tCtrl.test[$index]' ng-required='required' ng-maxlength='3'/>";
    var el = $compile(html)(scope);
    element.html("");
    element.append(el);
  }
}
});

They work fine with my angular code, but the problem is: They are not "recognized" as part of my form. That means, the parent FORM element does not change it's $pristine, $error, etc, status when inputs are modified.

How can I have the compiled inputs be treated as part of the form?

This plunkr is an example of the problem I'm having:

http://plnkr.co/edit/tR7loK45wXEFcBIsDeur?p=preview

Upvotes: 2

Views: 899

Answers (1)

harishr
harishr

Reputation: 18055

what you are doing is putting the element on dom after compiling it, and hence the ngmodel does not get a chance to hookup itself to the parent form.

what you are doing is:

1. create & compile element
2. place it in dom

as element is already compiled before making it to the dom.. it would never know of its parent form and hence wont link itself to the parent.

the sequence of step should have been:

1. create an element, 
2. place it in dom 
3. compile it. // now it will have a chance to hook up to the parent

so what you should rather do is:

   var el =angular.element('your html');
   element.append(el);
   $compile(el)(scope);

Upvotes: 2

Related Questions