Search code examples
javascriptangularjsformsangularjs-ng-include

Why I can't access a form object inside a ngInclude on angularJS?


I have a screen built with a several stacks of ng-includes. The last one, in special, I build the screen based on user configuration.

Sometimes, I have to show a Form in one of this included templates. And when my user click on save button, I have to validate if all fields in the form are valid.

In the meantime, when a try to access form object, to check for $valid, my form is undefined.

After a day fighting against it, I've discovered that ng-include process is not accepting my form object to be created.

I've created this plunker to see if it's really happening on a simple project, making a working form and not working one: http://plnkr.co/edit/4oMZYLgaYHJPoSZdSctI?p=preview

Basically, created a form, like this, with demanded angular attributes:

<form name="sampleForm">
    <input type="text" name="aws" required ng-model="myValue">
    <br/>myValue: "{{ myValue }}"
    <br/>

    <input type="text" name="aws" required ng-model="myValue">
    <br/>myValue: "{{ myValue }}"
</form>

And trying to access form object like this:

$scope.sampleForm.aws.$valid

And the result is:

$scope.sampleForm === undefined

Someone know how to solve this problem?


Solution

  • Since ng-include creates a new scope, $scope.sampleForm will be undefined from within the included page.

    The solution should be getting the ng-controller="formController" declaration inside of the included HTML page itself, which I think is also a better design, since I can't see a scenario where it's not "controlling" the form.

    The other non-included form obviously works as you might expect.

    Plunker