AngularJS $setValidity on childScope form

Problem

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?

Problem courtesy of: JoakimB

Solution

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

Solution courtesy of: Mark Rajcok

View additional discussion.

Like what you read? Give Angular.js Recipes a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.