TypeError: Cannot read property '$dirty' of undefined


I have an Angular form with name p24Form

<div ng-form="private2" name="p24Form" ng-show="freqSelect == '2.4'" novalidate="" class="ng-pristine ng-valid">
    <div class="form-group">
        <label class="col-sm-2 control-label">
            <span class="edit" data-pk="private_2">WiFi name</span>:
        <div class="col-sm-4">
            <input type="text" class="form-control ng-pristine ng-untouched ng-valid" name="freq2_name" ng-model="ssid">
            <!-- tooltips:  -->

I am trying to detect if it is dirty or change, then showing my save button accordingly.
I tried


if ($scope.p24Form.$dirty) {
    $scope.showSaveBtn = true;
    $scope.showSaveBtn = false;

Try #2

if ($scope.private2.$dirty) {
    $scope.showSaveBtn = true;
    $scope.showSaveBtn = false;

I kept got

TypeError: Cannot read property ‘$dirty’ of undefined

How can I debug this?


You need to access an input of your form to check if it’s dirty. For example:


As you pointed out, you should use the name attribute of the form to access it.

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.

    $scope.isDirty = $scope.myForm.$dirty;

Answered By – Jean-Michel Provencher

Answer Checked By – Pedro (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.