2

I have a pane system that includes three different forms inside my controller. Now, as I understand ng-include creates a childscope which makes it unavailable from the parent scope.

To solve the form data I passed the ng-model back in the function I run in ng-submit, but this is only 1 way.

In a normal situation I can do this:

HTML Form tag example
<form novalidate name="myForm" ng-submit="someFunction(form)">

HTML Form Field example
<input ng-model="form.first_name" name="first_name" type="text" pwtest required/>

Controller
$scope.myForm.first_name.$setValidity('required', false);

This works fine and my form data is return and I can send it on the way to my API and my field-state is also properly set.

Now to the problem..

HTML Form tag example
<form novalidate name="myForm" ng-submit="someFunction(form)">

HTML Form Field example
<input ng-model="form.first_name" name="first_name" type="text" pwtest required/>

Controller
$scope.myForm.first_name.$setValidity('required', false); <-- fails since myForm doesnt exist

This normaly works but now my form exists in a childscope and therefore myForm becomes undefined in my controller, as it should be of course since it doesnt exist in the scope.

Question is, how can I control my form field states in a childscope from my parent controller?

Community
  • 1
  • 1
JoakimB
  • 1,196
  • 2
  • 13
  • 19
  • Is adding a child controller an option? You could ng-submit to child controller method, where it can set the validity, then it could call a method on the parent controller. – Mark Rajcok Aug 22 '13 at 14:03
  • See also http://stackoverflow.com/questions/15818431/how-can-i-check-an-ng-included-forms-validity-from-the-parent-scope – Mark Rajcok Aug 22 '13 at 14:06
  • Perhaps, just have a feeling that it should be easier? But maybe it isnt. Could you perhaps give a small code snippet how it could look? – JoakimB Aug 22 '13 at 14:07

1 Answers1

4

As per the comments above, here is one way to solve the problem using a child controller:

<script type="text/ng-template" id="/form.html">
    <form novalidate name="myForm" ng-submit="someFn()" ng-controller="ChildFormCtrl">
       <input ng-model="form.first_name" name="first_name" type="text" required> 
       <br>{{myForm.first_name.$valid}}
    </form>
</script>

<div ng-controller="MyCtrl">
    <div ng-include="'/form.html'"></div>
</div>

function ChildFormCtrl($scope) {
    $scope.someFn = function () {
        console.log('child', $scope.form);
        $scope.myForm.first_name.$setValidity('required', false);
        $scope.parentFunction($scope.form);
    }
}
function MyCtrl($scope) {
    $scope.parentFunction = function (form) {
        console.log('parent', form);
    }
}

fiddle

Mark Rajcok
  • 362,217
  • 114
  • 495
  • 492