简体   繁体   中英

How to clear a form in an ng-include

I have an html template with a reusable modal that gets ng-included like this:

myPartial.html

... SOME HTML ...
<ng-include src="'form.html'"></ng-include>

modal.html

...
<form>
  <input ng-model="comment.value" />
  <button type="submit" ng-click="save(comment.value)" />
</form>
...

What is the best way to clear the form -- particularly from the controller if possible. I'd like to clear the form from my save() method after a successful http call, but since ng-include creates it's own scope, i'm not sure how to do this.

Here's a plunker to show my problem: http://plnkr.co/edit/zkxZOZr3f7sHJZfCiuoT?p=preview

If you take the contents of form.html and put them directly into index.html it works just fine.

You almost got it. Just initialize the comment instance in your controller and update the correct value in save. I believe the behaviour your experiencing is called "prototypal inheritance" and you can read about it at Understanding scopes . This is not exclusive to AngularJS btw, but can be found in regular JavaScript as well.

angular.module('app', []).controller('appcontroller', function($scope) {

  // create comment
  $scope.comment = { value: 'test' };
  $scope.save = function(value) {
    console.log('in here ');

    // and update comment.value, not comment.
    $scope.comment.value = null;
  };
});

I updated your plunker .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM