我有一个输入字段:
<input name="fName" type="text" class="form-control dude.firstName"
ng-trim="false"
ng-pattern="patterns.name"
ng-model="dude.firstName"
ng-model-options="{ updateOn: 'blur' }"
required>
<span class="error" ng-show="idForm.fName.$error.pattern">
Please only use letters, forward slashes, and hyphens
</span>
我的要求是这样的:
- 如果用户没有更改任何内容,则需要运行 saveIdentification
- 如果用户更改了某些内容并且无效,则停止并允许表单显示消息
如果用户更改了某些内容并且有效,则运行 saveIdentification
<span ng-show="localEditing.id=='SAVE'" tabindex="0" title="Save Changes" class="globalIcon-save action-edit-button" ng-click="(idForm.$pristine || (idForm.$dirty && idForm.$valid)) && saveIdentification()"> </span>
上述解决方案满足要求1和2,但不满足要求3。如果表单更改且有效,则不会保存。
最佳答案
请参阅下面的代码片段。我只是对您的代码做了一些细微的修改,以便在 saveIdentification
函数中接收表单对象作为参数。
注意,我添加了一个带有 ng-maxlength="3"
的输入,以便重现表单无效的场景(当输入文本大于3)
当满足您所描述的条件时,浏览器控制台(开发工具)中会记录“ran saveIdentification!”文本。
angular
.module('app', [])
.controller('myCtrl', function() {
var vm = this;
vm.wizard = {
saveIdentification: fnSaveIdentification
};
return vm.wizard;
function fnSaveIdentification(form) {debugger;
if (form && (form.$pristine || form.$valid)) { //<-- Condition here!
console.log('ran saveIdentification!');
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="myCtrl as ctrl">
<form name="myForm">
<input name="i1" type="text" ng-maxlength="3" ng-model="ctrl.input">
<a href="#" ng-click="ctrl.saveIdentification(myForm)">Submit</a>
<!-- Display message here!! (modify as you need it)-->
<span ng-show="myForm.$invalid">Form is invalid</span>
</form>
</div>
关于javascript - AngularJS:如果是原始的,则单击,或者如果脏且有效,则单击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45043356/