Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS: enable button on form input change

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

like image 894
Zak Kus Avatar asked Sep 18 '14 23:09

Zak Kus


People also ask

How to enable or disable Button in angular?

To disable button in Angular, we set the [disabled] attribute. to set the [disabled] attribute to 'disabled' if editmode is false . Otherwise, we set it to null to keep the button enabled.

How to add disabled attribute to Button in angular?

We can disable a button by passing the boolean value true to the disabled attribute. To enable it back, we need to set the isDisabled property value to false .

How to disable input field in angular js?

The ng-disabled directive sets the disabled attribute of a form field (input, select, or textarea). The form field will be disabled if the expression inside the ng-disabled attribute returns true. The ng-disabled directive is necessary to be able to shift the value between true and false .

How to disable input type in angular?

Disable the TextBox by adding the e-disabled to the input parent element and set disabled attribute to the input element.


1 Answers

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" />
like image 92
PSL Avatar answered Sep 25 '22 00:09

PSL