要想在angularjs使用$脏检查每当一个表单正在编辑要想、表单、正在编辑、angularjs

2023-09-13 04:59:13 作者:淡漠人情炎凉﹠

我试图检查每当我的形式被写入它的某些字段编辑。我读$脏应为任务工作,但我想不出什么,我在这里失踪:

I was trying to check whenever my form is being edited by writing some fields of it. I read $dirty should work for that task but I can't figure out what I'm missing here:

<!DOCTYPE html>
<html lang="en">
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="formCtrl">
  <form name = "myForm" novalidate>
    First Name:<br>
    <input type="text" ng-model="user.firstName"><br>
    Last Name:<br>
    <input type="text" ng-model="user.lastName">
    <br><br>
    <button ng-click="reset()">RESET</button>
  </form>
  <p> is Form dirty? {{isDirty}}<p>
  <p>form = {{user }}</p>
  <p>master = {{master}}</p>
</div>

<script>
var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
    $scope.master = {firstName:"John", lastName:"Doe"};
    $scope.reset = function() {
        $scope.user = angular.copy($scope.master);
    };
    $scope.reset();
    $scope.isDirty = $scope.myForm.$dirty;
});
</script>

</body>
</html>

我试图使标志isDirty为true,每当用户修改的形式。谢谢

I'm trying to make the flag isDirty to true whenever the user modifies the form. Thanks

推荐答案

您缺少名称属性在你的表单字段这是不启用表单验证这些领域。您需要为每个字段添加唯一的名称,这样它会加入 myForm会这些领域对象

You are missing name attributes in your form fields which are not enabling form validation for those field. You need to add unique name for each field so that it will get add those field in myForm object

标记

  <form name="myForm" novalidate>
    First Name:<br>
    <input type="text" name="firstName" ng-model="user.firstName"><br>
    Last Name:<br>
    <input type="text" name="lastName" ng-model="user.lastName">
    <br><br>
    <button ng-click="reset()">RESET</button>
  </form>

另外你正在访问 myForm会对象,它是什么,但表单对象,我将无法使用,直到获得DOM渲染, $ scope.myForm 将只是不确定在控制器动初始化的时候,如果你真的想访问 $ scope.myForm 从控制器,那么你需要把那个$在 $超时C $ç将在运行 $超时函数code下一消化周期。

Also you are accessing myForm object which is nothing but form object, I won't be available until DOM get rendered, $scope.myForm will be simply undefined at the time of controller initilization, If you really want to access $scope.myForm from controller then you need to put that code in $timeout that will run $timeout function code in next digest cycle.

  $timeout(function(){
    $scope.isDirty = $scope.myForm.$dirty;
  });

更新

有没有必要维持 isDirty 标志您需要更改此标志时,在形式上的任何变化 $脏国旗,而不是我会建议你使用 $ scope.myForm。$脏无论你想。你会通过 myForm会简单示。$脏这个标志会改变形式变脏。

There is no need to maintain isDirty flag you need to change this flag when any changes in form $dirty flag, instead of that I'd suggest you to use $scope.myForm.$dirty wherever you want. On you it would simply shown by myForm.$dirty this flag will change as form gets dirty.

工作Plunkr