javascriptangularjsangularjs-validationangularjs-forms

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>:
        </label>
        <div class="col-sm-4">
            <input type="text" class="form-control ng-pristine ng-untouched ng-valid" name="freq2_name" ng-model="ssid">
            <!-- tooltips:  -->
        </div>
    </div>
</div>

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

Try#1

if ($scope.p24Form.$dirty) {
    alert('dirty');
    $scope.showSaveBtn = true;
}else{
    $scope.showSaveBtn = false;
}

Try #2

if ($scope.private2.$dirty) {
    alert('dirty');
    $scope.showSaveBtn = true;
}else{
    $scope.showSaveBtn = false;
}

I kept got

TypeError: Cannot read property '$dirty' of undefined

How can I debug this?


Solution

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

    $scope.myForm.inputName.$dirty
    

    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.

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