angularjs - Why is $timeout needed when dynamically nesting ng-form in Angular to ensure child form links with parent form? -


i cannot seem avoid need generate dynamic sub forms in application working on. sub form working expected , sub form shows $invalid=true when 1 or more of it's inputs invalid. parent form has $invalid=false.

i have seen people achieve nested forms invalid sub forms invalidate parent form, can't seem dynamically without wrapping dynamic compiling of sub form in $timeout.

see plunker here

in above link have recreated scenario. have 3 forms. parent form, sub form created @ same time parent form, , dynamically created sub form.

if clear bottom existing sub form's input, invalidate parent form (parent form turns red).

if clear top dynamic form's input, not invalidate parent form (parent form remains green).

it begin work if stick addform method in $timeout:

// works! : when delete dynamic added sub form input // parent form becomes invalid //timeout(addform,0);   // fails! : when delete dynamic added sub form input text // parent form not become invalid addform(); 

it's great have workaround, understand why need $timeout , if there solution avoids use of $timeout.

dom manipulations should done in link phase , not in controller. see $compile

the link function responsible registering dom listeners updating dom. executed after template has been cloned. of directive logic put.

detailed explanation:

the problem lies in the angular formcontroller. @ intialization parent form controller instance. sub form created in controller phase - parent form initialization has not been finished. sub form won't find it's parent controller , can't register sub control element.

fromcontroller.js

//asks $scope fool bc controller module formcontroller.$inject = ['$element', '$attrs', '$scope', '$animate', '$interpolate']; function formcontroller(element, attrs, $scope, $animate, $interpolate) {   var form = this,       controls = [];    var parentform = form.$$parentform = element.parent().controller('form') || nullformctrl; 

plunker


Comments

Popular posts from this blog

powershell Start-Process exit code -1073741502 when used with Credential from a windows service environment -

twig - Using Twigbridge in a Laravel 5.1 Package -

c# - LINQ join Entities from HashSet's, Join vs Dictionary vs HashSet performance -