具有Form和$ setPristine的Angular 1.5组件 [英] Angular 1.5 Components with Form and $setPristine

查看:68
本文介绍了具有Form和$ setPristine的Angular 1.5组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Angular 1.5的组件中使用表单

I'm trying to use a form within a component in Angular 1.5

我有工作的形式,因为我有模型绑定,可以在提交时获取数据.因此,我90%都想成为我想去的地方,所缺少的是能够使用$ setPristine正确地重置表单.

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.

我尝试了几种方法,第一种是将表单传递为reset函数的参数.

I've attempted a couple of approaches the first was passing in the form as an argument to the reset function.

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
};

Plnkr中的完整代码

我还尝试将$ ctrl.userForm声明为空对象$ onInit,但这似乎也不起作用.删除$ setPristine行后,重置会清除表单数据,但从角度角度来看不会清除状态.

I also tried declaring $ctrl.userForm as an empty object $onInit, but that didn't seem to work either. With the $setPristine line removed the reset works in clearing the forms data but not it's state from an angular perspective.

关于我所缺少的东西有什么想法吗?

Any ideas on what I'm missing?

推荐答案

在plunkr中,您已经声明了下面的整个组件.

From your plunkr you have the entire component declared bellow.

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

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

  ctrl.reset();
}

该错误源自此行ctrl.reset();,在该行中您在不发送参数userForm的情况下调用了该方法.另外,您以错误的方式使用$setPristine,也不必将表单作为参数传递.

The error is originated from this line ctrl.reset(); where you call the method without sending the argument userForm. Also, you are using $setPristine in the wrong way and you don't have to pass the form as an argument either.

我建议您使用在控制器上声明的表单,如下所示:

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();
  };
}

注意:由于原始状态是默认状态,因此您不必致电ctrl.reset();.

Note: you don't have to call ctrl.reset(); because the pristine state is the default state.

这篇关于具有Form和$ setPristine的Angular 1.5组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆