简体   繁体   English

具有Form和$ setPristine的Angular 1.5组件

[英]Angular 1.5 Components with Form and $setPristine

I'm trying to use a form within a component in Angular 1.5 我正在尝试在Angular 1.5的组件中使用表单

I have the form working, in that I have model binding and can get to the data on submit. 我有工作的形式,因为我有模型绑定,可以在提交时获取数据。 So I'm 90% of where I want to be, what's missing is being able to reset the form correctly using $setPristine. 所以我有90%的工作要做,所缺少的是能够使用$ setPristine正确重置表单。

I've attempted a couple of approaches the first was passing in the form as an argument to the reset function. 我尝试了几种方法,第一种方法是将表单传递为reset函数的参数。

form.html form.html

<form name="$ctrl.userForm">
  ...
  <input class="btn btn-default" type="button" ng-click="$ctrl.reset($ctrl.userForm)" value="Reset" />
</form>

form.component.js form.component.js

ctrl.reset = function(userForm) {
    ctrl.user = {};
    userForm.$setPristine // Cannot read property '$setPristine' of undefined
};

Full code in Plnkr Plnkr中的完整代码

I also tried declaring $ctrl.userForm as an empty object $onInit, but that didn't seem to work either. 我还尝试将$ ctrl.userForm声明为空对象$ onInit,但这似乎也不起作用。 With the $setPristine line removed the reset works in clearing the forms data but not it's state from an angular perspective. 删除$ setPristine行后,重置将清除窗体数据,但从角度角度来看,它不是状态。

Any ideas on what I'm missing? 关于我所缺少的任何想法吗?

From your plunkr you have the entire component declared bellow. 您可以从plunkr中将整个组件声明为波纹管。

function formController() {
  var ctrl = this;
  ...

  ctrl.reset = function(userForm) {
    ctrl.user = {};
    userForm.$setPristine
  };

  ctrl.reset();
}

The error is originated from this line ctrl.reset(); 错误源自此行ctrl.reset(); where you call the method without sending the argument userForm . 在不发送参数userForm情况下调用方法的位置。 Also, you are using $setPristine in the wrong way and you don't have to pass the form as an argument either. 同样,您以错误的方式使用$setPristine$setPristine表单作为参数传递。

I sugest you to use the form declared on your controller like so: 我建议您使用在控制器上声明的表单,如下所示:

angular
  .module('application')
  .component('mkForm', {
    templateUrl: 'form.html',
    controller: formController
  });

function formController() {
  var ctrl = this;
  ctrl.master = {};

  ctrl.update = function(user) {
    ctrl.master = angular.copy(user);
  };

  ctrl.reset = function() {
    ctrl.user = {};
    ctrl.userForm.$setPristine();
  };
}

Note: you don't have to call ctrl.reset(); 注意:您不必调用ctrl.reset(); because the pristine state is the default state. 因为原始状态是默认状态。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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