1

I need to be able to see in the Angular controller if the datepicker is pristine or not. Tried all sorts of things including sending the pristine value in a method but cannot get this value. Below is the view code:

<form name="myForm">
                                <!-- Datepicker From -->
                                <div class="small-6 medium-5 large-2 columns" ng-if="vm.subViewActive">
                                    <div class="input-group">
                                        <input name="valuationDatePickerFrom" ng-model="name" type="text" class="datepicker" id="valuationDatePickerFrom" placeholder="DD/MM/YYYY" pikaday="vm.datePickerFrom" on-select="vm.selectStartDate(pikaday)" year-range="{{ vm.yearRange }}" >
                                        <div class="input-group-addon">
                                            <label for="valuationDatePickerFrom" class="postfix">
                                                <i class="fa fa-calendar"></i> From
                                            </label>
                                        </div>
                                    </div>
                                </div>
                </form>

and then I also tried :

var isPristine = $scope.myForm.valuationDatePickerFrom.$pristine;
console.log(isPristine);  

in my controller but cannot get the pristine value. Read lots of posts here but mainly to do with CSS classes and front-end control or setting the pristine state from the backend not getting or checking the pristine state.

Thanks anybody that can help.

Afshin Ghazi
  • 2,784
  • 4
  • 23
  • 37

2 Answers2

2

You are using:

var isPristine = $scope.myForm.valuationDatePickerFrom.$pristine;

but your form's name is not myForm.

Change <input name="name"... <input name="valuationDatePickerFrom"...

Then you can use:

var isPristine = $scope.userForm.valuationDatePickerFrom.$pristine;

Also, the controller is getting called before the view is created, so no myForm exists at the time the controller runs. Try adding a $timeout like so:

$timeout(function() {
  var isPristine = $scope.userForm.valuationDatePickerFrom.$pristine;
  console.log(isPristine);
}, 100);

plunkr

Raphael Rafatpanah
  • 19,082
  • 25
  • 92
  • 158
1

The above solution only works on page load, but you need to know this value when the page is being used. Instead pass the value to the controller when an action happens:

<form name="myForm"> <input type="text" name="valuationDatePickerFrom" ng-model="valuationDatePicker" ng-blur="alerty(myForm.$pristine)"> </form>

.controller('MainController', function($scope) { $scope.alerty = function(isPristine){ alert('isPristine: ' + isPristine); };

https://plnkr.co/edit/f0EWvYmoXCn8UOH3QCfE?p=preview

Jim McNeely
  • 798
  • 5
  • 7