我想在ng-book jsbin中複製一個示例。
這裏是我的plnkr
app.js
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.fields = [{placeholder: 'Email', isRequired: true},
{placeholder: 'Password', isRequired: true},
{placeholder: 'Comment(Optional)', isRequired: false}]
$scope.formSubmit = function(){
for (var i=0; i < $scope.fields.length; i++)
{ var obj = $scope.fields[i]
for (var key in obj){
if(obj.hasOwnProperty(key)){
alert(key + ' : ' + obj[key])
}
}
}
}
});
HTML
<html ng-app="plunker">
<head><script data-require="[email protected]" src="https://code.angularjs.org/1.2.22/angular.js" data-semver="1.2.22"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<form name='main_form' ng-submit='formSubmit()' novalidate>
<div ng-repeat="field in fields" ng-form="dynamic_form">
<input type='text'
name='dynamic_input'
ng-required='field.isRequired'
ng-model='field.name'
placeholder='{{field.placeholder}}'>
<div ng-show="dynamic_form.dynamic_input.$dirty && dynamic_form.dynamic_input.$invalid">
<span ng-show="dynamic_form.dynamic_input.$error.required"> This field is required.</span>
</div>
</div>
<button type='submit' ng-diabled="main_form.$pristine && main_form.$invalid">Submit All</button>
</form>
</body>
</html>
我現在面臨的問題在這裏:
- 提交未禁用按鈕
- 未顯示所需字段的錯誤。
- 如果我點擊提交,我也會獲得$ hash key以及alert。這是爲什麼?
謝謝。
我可以向您展示另一個以不同方式進行驗證的例子,或者您完全想要這種方式嗎? – 2014-08-29 14:33:40
當然。最受歡迎的。 – Indyarocks 2014-08-29 16:48:04