Why form undefined inside ng-include when checking

2019-01-09 02:58发布

问题:

The following code throws the error "TypeError: Cannot read property '$pristine' of undefined" when I click the "check" button.

app.controller('MainCtrl', function($scope) {
  // other stuff
})

.controller('Ctrl2', function($scope) {
  $scope.product = {description:'pump'};
  $scope.output = 'unknown';
  // uncomment to avoid undefined error, still can't see $pristine
  // $scope.formHolder = {};
  $scope.checkForm = function() {
    $scope.descriptionTest = $scope.product.description;
    if ($scope.formHolder.productForm.$pristine) {
      $scope.output = 'yes';
    }
    if ($scope.formHolder.productForm.$dirty) {
      $scope.output = 'no' 
    }
  }
});

html

  <body ng-controller="MainCtrl">
    <div >
      <ng-include ng-controller="Ctrl2" src="'myForm.html'"></ng-include>
    </div>
  </body>

myForm.html

<form name="productForm" novalidate>
  <h2>myForm</h2>
  description: <input type="text" name="description" ng-model="product.description"/>
  <br>
  <button ng-click="checkForm()">Check Form</button>
  <br>
  Form Pristine: {{output}}
  <br><br>
  I can see the description: {{descriptionTest}}
</form>

plunkr

The problem is that my Ctrl2 can't see the productForm. At first I thought this had to do with the prototypical inheriting that ng-include does when it makes a child scope, so I tried adding a variable in Ctrl2:

$scope.productForm = {}; 

This got rid of the error, but my controller still wasn't correctly seeing $pristine or $dirty.

I finally got it working by adding a $scope.formHolder object above the productForm:

plunkr

.controller('Ctrl2', function($scope) {
  $scope.product = {description:'pump'};
  $scope.output = 'unknown';
  // uncomment to avoid undefined error, still can't see $pristine
  $scope.formHolder = {};
  $scope.checkForm = function() {
    $scope.descriptionTest = $scope.product.description;
    if ($scope.formHolder.productForm.$pristine) {
      $scope.output = 'yes';
    }
    if ($scope.formHolder.productForm.$dirty) {
      $scope.output = 'no' 
    }
  }
});

html

<form name="formHolder.productForm" novalidate>

Why does this work? And is there a better way to do this?

I ended up this way because I had a working form & controller / template that I wanted to reuse somewhere else. I should probably make a directive, but everything worked fine except the $pristine and $dirty features of the form--all the ng-model vars were passed correctly.

How can I set a form contained inside a ng-include to be prestine? has an answer that "breaks all the rules" but seemed more complicated.

When I write when does the form Controller add $pristine to the scope, and to what scope?

Edit / Answer:

My original question can be boiled down to confusion about how the form directive writes to the scope. I had the impression that it would take the thing in

<form name="productForm">...

and add properties to it, like

$scope.productForm.$pristine = function() {...}

however, it writes directly on top of productForm:

$scope.productForm = formObject;

So, the form object is stored in the Child and not the parent as explained in the selected answer.

The key nugget in child scope inheritance that helped me is that the chain is consulted in reading, but not writing. So if you set something like childScope.myThing.property = '123', while it looks like a write, it first has to do a read to find out what myThing is. Whereas setting childScope.myThing = '567' is a direct write, and doesn't involve looking at the parent chain at all. This is all better explained in: What are the nuances of scope prototypal / prototypical inheritance in AngularJS?

回答1:

To understand why the solution with formHolder work you have to understand JavaScript prototypes chain first. Let's illustrate the first case without formHolder in the following pseudo code:

$parentScope = {
  //I'm a parent scope inside Ctrl2
  productForm:{} //to avoid undefined reference error 
}

$childScope = {
  //I'm a child scope created by by ng-include 
  __protototype__: $parentScope 
}

When the form directive is parsed it creates FormController which is set on the $scope property under key indicated in name attribute value. This is pretty much equivalent to:

$childScope.productForm = $formCtrl;

After which the 2 scopes look like this:

$parentScope = {
  //I'm a parent scope inside Ctrl2
  productForm:{} //to avoid undefined reference error 
}

$childScope = {
  //I'm a child scope created by by ng-include 
  productForm: $formCtrl

  __protototype__: $parentScope 
}

So you actually ended up with 2 properties on different scopes holding different objects. Now in the second case you have the following situation:

$parentScope = {
  //I'm a parent scope inside Ctrl2
  formHolder:{} //to avoid undefined reference error 
}

$childScope = {
  //I'm a child scope created by by ng-include 
  __protototype__: $parentScope 
}

When the form directive is setting FormController instance on the $scope this time it uses different property chain:

$childScope.formHolder.productForm = $formCtrl;

Which is equivalent to writing:

var formHolder = $childScope.formHolder; //since formHolder isn't defined on $childScope
//the JS runtime will look for it in the prototypes chain and find it inside $parentScope
//so here formHolder is the very same object you created and set on $parentScope
formHolder.productForm = $formCtrl;

Hope it helps to understand why the second option works. As for the second part of you question - your solution is simple and perfectly viable - but there are couple of other ways to handle it which is best depends on the actual usage context:

  • using directive without child scope to extract common markup and parts of functionality
  • using directive with child scope that would communicate state changes either via direct parent scope property access or via emitted events
  • using a custom include directive that would not create child scope


回答2:

Just define the variable (empty object) in the controller and use it while defining your form. Since angular JS uses scope prototypes under the hood, when form will try to access the inner scope (to bootstrap the variable), it will first go via scope chain and try to find the same variable in the parent's scope.

<!—- The vars should live in the controller. I placed them here for the example. -—>
<div ng-controller=“controllerName” ng-init="form={}; model={}" >
    <div ng-include=“ ‘path-to-the-template’ ”></div>
</div>

<!—- Inside path-to-the-template -—>
<form name="form.createUser">
    <input name="name" ng-model="model.name" />
    <input name="email" ng-model="model.email" />
</form>

Link for reference http://blog.152.org/2014/07/angular-form-element-not-attaching-to.html



回答3:

I know that this is a old question, but i had a similar problem, and i changed the html and included my ng-controller within the html file.

So instead of

<ng-include ng-controller="Ctrl2" src="'myForm.html'"></ng-include>

Change it too

<ng-include="'myForm.html'"></ng-include>

And then in the myForm.html file, wrap the code in a div, and add the ng-controller attribute, so your myForm.html would become

<div ng-controller="Ctrl2">
    <form name="productForm" novalidate>
      <h2>myForm</h2>
      description: <input type="text" name="description" ng-model="product.description"/>
      <br>
      <button ng-click="checkForm()">Check Form</button>
      <br>
      Form Pristine: {{output}}
      <br><br>
      I can see the description: {{descriptionTest}}
    </form>
</div>

Now your child controller is within the ng-include scope