我有一个包含多个子表单的父表单(例如http://jsfiddle.net/riemersebastian/9zr00ear/3/)
当用户更改任何字段时,相应的子窗体和父窗体将得到ng-脏类,以指示某些内容已经更改。
我在每个子表单上都有一个保存按钮(实际上是一个链接),它保存了所有的子表单更改并调用子表单。$setPristine来更新子表单的状态。
但是,我希望父窗体在不再存在脏子窗体时也会注意到,从而删除它的“ng-脏”类。
我想出了一个解决方案:http://jsfiddle.net/riemersebastian/9zr00ear/3/
正如您所看到的,我使用jQuery手动签入控制器,如果仍然有标记为脏的子窗体,如果没有,则设置父窗体原始。为此,我需要使用jQuery来延迟$timeout,否则$setPristine的调用可能还没有更改DOM,因此父表单不会被更新。
我想知道,有什么更好的方法吗?
以下是代码:
var myApp = angular.module('myApp',[]);
myApp.controller('FirstCtrl', ['$scope', '$timeout', function($scope, $timeout) {
$scope.setFormPristine = function(subForm) {
console.log(subForm);
subForm.$setPristine();
$timeout(function() {
if (!($('body').find(".subForm").is(".ng-dirty"))) {
console.log("none is dirty, set main form pristine")
$scope.form.$setPristine();
}
}, 10);
}
}]);
angular.bootstrap(document, ['myApp']);<body>
<div ng-controller="FirstCtrl">
<div>
(outer) form is dirty? <b>{{ form.$dirty }} </b>
</div>
<form name="form" ng-init="variants = [{duration:10, price:100}, {duration:30, price:200}]">
<div>
<div class="subForm" ng-repeat="variant in variants" ng-form="subForm">
<div>
<label>Duration:</label>
<input name="duration" ng-model="variant.duration"/>
</div>
<div>
<label>Price:</label>
<input name="price" ng-model="variant.price"/>
</div>
<a href="" ng-click="setFormPristine(subForm)">Reset Form to pristine</a>
<div>
(inner) subform is dirty? <b>{{ subForm.$dirty }} </b>
</div>
<br></br>
</div>
</div>
</form>
</div>
</body>发布于 2015-02-26 19:41:43
阿格!把jquery弄出来!;)
我的第一个解决方案是指令和控制器api,让子表单将通知推送到主表单,一些伪代码:
app.directice('mainForm', function($scope) {
return {
restrict: 'E',
transclude: true,
controllerAs: 'mainCtrl',
controller: function($scope){
this.publishState = function (childIsDirty) {
if (!$scope.parentForm.$dirty && !childIsDirty)
$scope.parentForm.$setPristine();
if (childIsDirty) {
$scope.parentForm.$setDirty();
}
}
},
templateUrl: 'parentForm.html'
};
});
app.directice('subForm', function ($scope) {
return {
require: '^parentForm',
restrict: 'A',
transclude: true,
controllerAs : 'viewModel',
link: function (scope, element, attrs, parentForm) {
console.log("Hey I am subForm!");
scope.$watch('subForm1.$dirty', function(isDirty, wasDirty) {
parentForm.publishState(isDirty);
});
},
controller : function() {
var viewModel = this;
viewModel.myData = "Hello World";
},
templateUrl: 'subForm.html'
};
});使用html时,您应该避免嵌套表单,因为它们被认为是糟糕的html表单(抱歉,必须这样做),它们实际上并不需要嵌套,因为所需的命令只会查看已经注入的所有其他控制器。
<div>
<parent-form></parent-form>
<script type="text/ng-template" id="parentForm.html">
<form name="parentForm">
content
</form>
<form name="subForm1" sub-form></form>
</script>
<script type="text/ng-template" id="subForm.html">
<div>
<input type="text" name="myInput" ng-model="viewModel.myData" >
</div>
</script>
</div>如果不想链接,也可以将主表单方法传递到子表单的作用域“&”中。
另一种方法是创建一个共享服务/工厂,用于发布更改,然后表单控制器将监视属性或将其方法注册到单例工厂。
https://stackoverflow.com/questions/28748901
复制相似问题