steve k steve k - 6 months ago 141
AngularJS Question

$setPristine() not working.

**** Note I cut out some of my other functions so that the code could be read through faster. I cannot clear the form. when i click the button with the cancel function. I thought I could set a default form, but this doesn't make a difference.

<form name="myForm" novalidate ng-submit="submit()">
<table class="mealCost">

<!-- descriptions -->
<tr>
<td> Base Meal Price: </td>
<td><input type="number" name="price" ng-model="mealPrice" required></td>
</tr>
<!-- waiter puts in the info -->
<tr>
<td> Tax Rate: % </td>
<td><input type="number" step="0.01" name="tax" ng-model="mealTax" required></td>

</tr>

<tr>
<td> Tip Percentage: % </td>
<td><input type="number" name="tip" step="0.01" ng-model="tipPercent" required></td>

</tr>

</table>

<p class="userResponse">
<input type="submit" value="Submit">
<!-- <input id="cancel" type="submit" value="Cancel" ng-submit="cancel(original)"> -->
<button ng-click="cancel()">Start Over</button>
</p>

</form>


Here is my javascript I am trying to set my form to $setPristine using the button command wiht ng-click. I though that setting a default form would help but nothing happens on submit

var app = angular.module('myApp',[]).
controller('costController', function($scope) {
// $scope.ready= false;
$scope.mealPrice ="" ;
$scope.mealTax = 0.05;
$scope.tipPercent =0.05;
// possibly could do

var defaultForm={
price: "",
tax: "",
tip:""
}

$scope.cancel = function() {
$scope.myForm.$setPristine();
$scope.user = angular.copy(defaultForm);
console.log('empty');
}

Answer

I think you're using it wrong.

$setPristine:

"This method can be called to remove the 'ng-dirty' class and set the form to its pristine state (ng-pristine class). This method will also propagate to all the controls contained in this form."

So this only clears classes but not the $scope variables. You do reset a $scope.user variable, could say:

Add 'user.' in front of every model in the Html

ng-model="user.tipPercent"
ng-model="user.mealTax"
ng-model="user.mealPrice"

And replace this in your JS:

// $scope.ready= false;
        $scope.mealPrice ="" ;
        $scope.mealTax = 0.05;
        $scope.tipPercent =0.05; 
        //  possibly could do 

        var defaultForm={
            price: "",
            tax: "",
            tip:""
        }

$scope.cancel = function() {
            $scope.myForm.$setPristine();
            $scope.user = angular.copy(defaultForm);
            console.log('empty');
        }

to this:

var defaultForm = {
    mealPrice : "",
    mealTax : 0.05,
    tipPercent : 0.05
}

$scope.user = angular.copy(defaultForm);

$scope.cancel = function () {
    $scope.myForm.$setPristine();
    $scope.user = angular.copy(defaultForm);
    console.log('empty');
}