Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set the value of a form to pristine from a home controller?

Tags:

angularjs

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.

like image 551
Samantha J T Star Avatar asked Mar 03 '14 04:03

Samantha J T Star


People also ask

How do you set a pristine form?

$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.

What is pristine in form control?

"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.

How do you set a pristine to a false form?

Using $setPristine will set the $pristine property of the form to true and $dirty to false. $setDirty will do the contrary.

What is pristine in angular form?

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.


1 Answers

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

like image 94
Matt Way Avatar answered Oct 11 '22 18:10

Matt Way