I have a parent form containing multiple sub forms (e.g. http://ift.tt/1AbPRP0)
When the user changes any of the fields, the respective sub form and the parent form get the class ng-dirty to indicate something has changed.
I have also a save-button (actually it is a link) on each of the sub form which saves all sub-form changes and calls subform.$setPristine to update the state of the subform.
However, I would like the parent form to also take notice when there are no dirty subforms anymore and thus remove its' ng-dirty class.
I have come up with this solution: http://ift.tt/1AbPRP0
As you can see I manually check in the controller using jQuery if there are any subforms left marked as dirty, and if not I set the parent form pristine. For that I need to delay the jQuery using $timeout otherwise the call of $setPristine might not have yet changed the DOM and thus the parent form would not be updated.
I would like to know, is there a better way of doing this?
Here is the code:
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>
Aucun commentaire:
Enregistrer un commentaire