0

I've looked for an answer to this and come across several posts, but none of them are working for me.

I want to do something simple. I have a button that is invisible until the form is dirty. This works great if I manually dirty the form. However, I am saving the data. when the form is loaded, the saved data is populated, but the form isn't dirty when the backend data is updated this way.

So, I figured I'd just set the form to dirty manually. But I am receiving "undefined" errors.

$scope.myForm = > undefined
$scope.$myForm => undefined
myForm = > returns the form object
myForm.myField = > returns the field
myForm.myField.$dirty => returns undefined
myForm.myField.$setDirty() = > returns "$setDirty is not a function"
this (inside my controller) = > returns and empty object

I'm using angular 1.6.6 I've read: Angular.js programmatically setting a form field to dirty,

How to explicitly set a text box in a form to dirty?,

How to set a particular field in a form to dirty in angularjs 1.3

My basic form:

<div ng-controller="appCtrl">
    <form name="myForm">
        <input name="myField" ng-model="myField" />
        <div ng-click="doSomething()" ng-show="myForm.myField.$dirty">Submit</div>
    </form>
</div>

I've added a plunker that shows the issue that I am having. https://plnkr.co/edit/ZUWywfOj329g6sviHIZf?p=preview

4

1 回答 1

1

问题是在执行控制器中的代码的那一刻,表单还没有在dom中创建,所以解决方案是在表单初始化时调用你的数据初始化。

<form name="myForm" ng-init="formInit()">

控制器:

$scope.formInit = function() {
    $timeout(function() {
      $scope.myForm.$setDirty(); 
    })
}

这将起作用。

现在我只想说,为什么要使用dirty来显示提交表单?为什么不使用 required 和 myForm.$valid 进行验证?

为什么不直接使用:

<div ng-controller="appCtrl">
    <form name="myForm">
        <input name="myField" ng-model="myField" />
        <div ng-click="doSomething()" ng-show="myField">Submit</div>
    </form>
</div>
于 2017-09-24T03:32:39.300 回答