我如何表示 AngularJS 中哪些输入字段发生了变化 [英] How can I denote which input fields have changed in AngularJS

查看:24
本文介绍了我如何表示 AngularJS 中哪些输入字段发生了变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个将数据放入 API 的编辑表单 (user.html),但我想避免将所有数据放入表单中.我只想放置已更改的项目.

我已经看到在处理表单时使用了dirty 和 pristine,但这适用于表单中的任何更改.我也看到了 ng-change 的使用,但我不想触发对一个元素的更改的操作,只是表示更改的元素应该包含在 PUT 中.

有没有人找到一种方法来仅表示已更改的输入字段?

解决方案

如果你把输入放在一个带有 name 属性的 form 中,然后给输入一个 name 属性,您还可以访问输入的 $pristine 属性.

<表单名称="myForm"><input type="text" name="first" ng-model="firstName"><input type="text" name="last" ng-model="lastName"></表单>

app.controller('MyController', function($scope) {//在这里你可以访问输入的 `$pristine` 属性console.log($scope.myForm.first.$pristine);console.log($scope.myForm.last.$pristine);});

您可以使用 $scope.myForm.$pristine 来查看 任何 字段是否已更改,以及每个输入的 $pristine 属性表单上的属性以查看该输入是否已更改.您甚至可以遍历 myForm 对象(非输入字段对象的键以 $ 为前缀):

angular.forEach($scope.myForm, function(value, key) {if(key[0] == '$') 返回;console.log(key, value.$pristine)});//首先,真//最后,假

I'm working on an edit form (user.html) that PUTs data to an API, but I'd like to avoid PUTting all the data in the form. I'd like to PUT just the changed items.

I've seen the use of dirty and pristine when working with forms, but this applies to any change in the form. I've also seen the use of ng-change, but I don't want to trigger an action on a change to one element, just denote that the changed element should be included in the PUT.

Anyone found a way to denote only the input fields that have changed?

解决方案

If you put the input in a form with a name attribute and then give the input a name attribute, you can also access the input's $pristine property.

<div ng-controller="MyController">
  <form name="myForm">
    <input type="text" name="first" ng-model="firstName">
    <input type="text" name="last" ng-model="lastName">
  </form>
</div>

app.controller('MyController', function($scope) {
  // Here you have access to the inputs' `$pristine` property
  console.log($scope.myForm.first.$pristine);
  console.log($scope.myForm.last.$pristine);
});

You can use $scope.myForm.$pristine to see if any fields have changed, and the $pristine property on each input's property on the form to see if that input has changed. You can even iterate over the myForm object (non-input-field objects have keys prefixed with a $):

angular.forEach($scope.myForm, function(value, key) {
  if(key[0] == '$') return;
  console.log(key, value.$pristine)
});
// first, true
// last, false

这篇关于我如何表示 AngularJS 中哪些输入字段发生了变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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