Javascript AngularJS:启用表单输入更改按钮
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25924103/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
AngularJS: enable button on form input change
提问by Zak Kus
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
我天真的方法是为每个设置 enableButton 标志的输入添加一个 ng-change 属性
<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"...)
但这似乎很乏味和重复(我们有很多选择),并且希望有一些简单的东西(比如“form.$hasChanged”...)
回答by PSL
Instead of setting a flag n change of any input of form, you should use the angular built in $dirtyproperty on the form controller object. It tells whether the user has interacted with the form's elements.
您应该使用$dirty表单控制器对象上的angular 内置属性,而不是设置任何表单输入的标志 n 更改。它告诉用户是否与表单的元素进行了交互。
<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 $pristineflag you could do
使用$pristine标志你可以做
<button ng-disabled="form.$pristine" type="submit" />
Similarly if you have validators on the form you could as well make use of $validproperty, example disable the button if the form is invalid or pristine
同样,如果表单上有验证器,您也可以使用$valid属性,例如,如果表单无效或原始,则禁用按钮
<button ng-disabled="form.$pristine|| form.$invalid" type="submit" />

