我正在尝试在ng-repeat中创建表单,除了提交按钮之外一切正常。提交按主要形式放置的按钮对所有子表单都是通用的。
如果点击了提交按钮,mainForm.$submitted
会更新,但userForm.$submitted
不会更改。那有什么工作吗?
angular.module("sampleApp", [])
.controller('sampleCtrl', function($scope) {
$scope.users = [{},{}];
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.js"></script>
<div ng-app="sampleApp" ng-controller="sampleCtrl">
<form name="mainForm" novalidate>
<input type="text" name="school" ng-model="school" required>
main form input valid=>{{mainForm.school.$valid}}
<div ng-repeat="user in users">
<ng-form name="userForm">
<input type="text" ng-model="user.name" name="name" required>
sub form input valid=>{{userForm.name.$valid}} | sub form submit=>{{userForm.$submitted}}
</ng-form>
</div>
<button type="submit">Submit</button>
Form valid=>{{mainForm.$valid}} | Main From submit => {{mainForm.$submitted}}
</form>
</div>
&#13;
答案 0 :(得分:1)
因此,我在按钮中添加了ng-click
处理程序,以便您也可以设置内部表单的提交状态。
我唯一的困难是实际获得表单引用,但我添加了$scope.setUserForm
函数,该函数使用ng-init
调用。解决方案模式来自:https://stackoverflow.com/a/23862411/1688441
另外,请记住,您需要一组userForms来保留引用。单击时,您将遍历这些元素并设置提交。
angular.module("sampleApp", [])
.controller('sampleCtrl', function($scope) {
$scope.UserForms = [];
$scope.setUserForm = function(form) {
$scope.UserForm = form;
$scope.UserForms.push(form);
}
$scope.forms = {};
$scope.users = [{}, {}];
$scope.handleClick = function() {
$scope.UserForms.forEach(function(element) {
element.$submitted = true;
});
};
})
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.js"></script>
<div ng-app="sampleApp" ng-controller="sampleCtrl">
<form name="mainForm" novalidate>
<input type="text" name="school" ng-model="school" required>
input valid=>{{mainForm.school.$valid}}
<div ng-repeat="user in users">
<ng-form name="userForm">
<div ng-init="setUserForm(userForm);"></div>
<input type="text" ng-model="user.name" name="name" required>
input valid=>{{userForm.name.$valid}} | form submit=>{{userForm.$submitted}}
</ng-form>
</div>
<button type="submit" ng-click="handleClick()">Submit</button>
Form valid=>{{mainForm.$valid}} | From submit => {{mainForm.$submitted}}
</form>
</div>
&#13;