Wayne F. Kaskie Wayne F. Kaskie - 27 days ago 10
AngularJS Question

Cannot set a form field to dirty

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

Answer Source

The issue is that the form is not still created in dom in the moment when the code in the controller is executed, so solution is to call your data initialization when the form is inited.

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

controller:

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

This will work.

Now I just want to say, why do you use dirty for displaying the submit form? Why not validation with required and myForm.$valid ?

Why not just using:

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