由于您想为其他表单字段重用相同的代码,并且每个表单字段的验证逻辑似乎都相似,所以我找不到任何有助于重用代码的ngForm 。相反,我会建议一种不同的方法,您不使用 ngForm 并自己在 js 中进行验证。这样,您可以在任何地方重用该方法。
这是 jsFiddle 的链接:http:
//jsfiddle.net/rCDg8/1/
<div ng-app>
<div ng-controller="DemoCtrl">
<form name="accountForm" ng-submit="submit()">
<div class="control-group" ng-class="class">
<label for="name" class="control-label">Company Name:</label>
<input type="text" name="name" ng-model="account.name" ng-change="validateEntry(account.name)" required></input>
<span class="help-inline" ng-show="accountForm.$dirty||accountForm.$invalid">{{msg}}</span>
</div>
</form>
</div>
</div>
控制器:
function DemoCtrl($scope) {
var longName = 'Name too long';
var nameRequired = 'Name is required!';
$scope.class = '';
$scope.showMsg = false;
$scope.validateEntry = function (validateItem) {
if (angular.isDefined(validateItem)) {
if (validateItem.length > 50) {
showErrorMsg(longName);
} else if (validateItem.length === 0) {
showErrorMsg(nameRequired);
} else {
$scope.class = '';
$scope.showMsg = false;
$scope.accountForm.$dirty = false;
$scope.accountForm.$pristine = true;
}
} else {
showErrorMsg(nameRequired);
}
};
$scope.submit = function(){
alert('IS Form Dirty: '+$scope.accountForm.$dirty);
};
function showErrorMsg(msg) {
$scope.class = 'error';
$scope.showMsg = true;
$scope.msg = msg;
$scope.accountForm.$dirty = true;
}
};