19

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

1 Answer 1

41

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" />
Sign up to request clarification or add additional context in comments.

3 Comments

So what if the user actually makes the form $dirty but then deletes the change. is it possible to check to see if there is actually a change in the fields before enabling the button
@Flash did you get an answer on this?
@HimalayMajumdar I ended up installing this library: github.com/betsol/angular-input-modified it worked perferctly

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.