Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
51
rated 0 times [  54] [ 3]  / answers: 1 / hits: 35247  / 10 Years ago, thu, september 18, 2014, 12:00:00

I have an app with a lot of settings in long form pages. You are expected to go to the pages to view the current settings, or to update them.



I would like to make it so that the update button is only enabled if someone actually changes the current inputs.



My naive approach would be to add an ng-change attribute to every input that sets the enableButton flag



<form name='form' ng-submit=submit()>
<input type=sometype ng-model='something1' ng-change=formChanged=true></input>
...
<input ng-model='somethingN' ng-change=formChanged=true></input>
<button ng-disabled=!formChanged type=submit />
</form>


but this seems tedious and repetitive (we have a lot of options), and was hoping for something simple (something like form.$hasChanged...)


More From » angularjs

 Answers
70

Instead of setting a flag n change of any input of form, you should use the angular built in $dirty property on the form controller object. It tells whether the user has interacted with the form's elements.



<form name='form' ng-submit=submit()>
<input name=some1 type=sometype ng-model='something1' ></input>
...
<input name=some2 ng-model='somethingN' ></input>
<button ng-disabled=!form.$dirty type=submit />
</form>


Using $pristine flag you could do



<button ng-disabled=form.$pristine type=submit />


Similarly if you have validators on the form you could as well make use of $valid property, example disable the button if the form is invalid or pristine



<button ng-disabled=form.$pristine|| form.$invalid type=submit />

[#69404] Wednesday, September 17, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
shylaelisan

Total Points: 37
Total Questions: 94
Total Answers: 110

Location: Angola
Member since Tue, May 5, 2020
4 Years ago
;