I have this situation:
<body ng-controller="HomeCtrl">
<div ng-controller="MainCtrl">
<form name="mainForm" >
<button type"button" ng-click="mp1()">Make Pristine 1</button>
<button type"button" ng-click="mp2()">Make Pristine 2</button>
This works in MainCtrl:
app.controller('MainCtrl', function($scope) {
$scope.mp2 = function() {
$scope.mainForm.$setPristine();
}
});
This doesn't work in HomeCtrl:
app.controller('HomeCtrl', function($scope) {
$scope.mp1 = function() {
$scope.mainForm.$setPristine();
}
});
Here's a plunkr that show the problem: Example
What I am trying to do is to get the validity checks and the ability to set pristine both working. I tried different combinations of using and ngForm, setting the form as an object in the outer scope etc. Still can't get it all to work for both. Note that I really need to do the $setPristine in the HomeCtrl as there are different MainCtrl's and I don't want to reimplement the code a lot of times.
$setPristine(); Sets the form to its pristine state. This method sets the form's $pristine state to true, the $dirty state to false, removes the ng-dirty class and adds the ng-pristine class.
"pristine" means the user hasn't changed the value since it was displayed in this form. So given a user has an autocomplete input that looks up airports nearby, when the user selects an option then we set the value of the FormControl to the selected option.
Using $setPristine will set the $pristine property of the form to true and $dirty to false. $setDirty will do the contrary.
ng-pristine The field has not been modified yet. ng-dirty The field has been modified. ng-valid The field content is valid. ng-invalid The field content is not valid.
You need to solve the nested scope issue by wrapping the form object in a container:
<form name="cont.mainForm">
Then setup the cont
object in you highest level controller
$scope.cont = {};
Then use the main form similarly to what you have in your controllers:
$scope.cont.mainForm.$setPristine();
Here is an updated plunk for you: http://plnkr.co/edit/VKY7PlwZgUuVN6jfpAG8?p=preview
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With