Last active
July 12, 2016 17:20
-
-
Save marcomafessolli/a3e365c78eafb488797de40c9f32dd42 to your computer and use it in GitHub Desktop.
Angular / Isolated nested form
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// credits to: http://jsfiddle.net/gikoo/eLv95st4 | |
'use strict'; | |
angular.module('m.isolate.form') | |
.directive('isolateForm', [function () { | |
return { | |
restrict: 'A', | |
require: '?form', | |
link: function (scope, elm, attrs, ctrl) { | |
if (!ctrl) { | |
return; | |
} | |
// Do a copy of the controller | |
var ctrlCopy = {}; | |
angular.copy(ctrl, ctrlCopy); | |
// Get the parent of the form | |
var parent = elm.parent().controller('form'); | |
// Remove parent link to the controller | |
parent.$removeControl(ctrl); | |
// Replace form controller with a "isolated form" | |
var isolatedFormCtrl = { | |
$setValidity: function (validationToken, isValid, control) { | |
ctrlCopy.$setValidity(validationToken, isValid, control); | |
parent.$setValidity(validationToken, true, ctrl); | |
}, | |
$setDirty: function () { | |
elm.removeClass('ng-pristine').addClass('ng-dirty'); | |
ctrl.$dirty = true; | |
ctrl.$pristine = false; | |
}, | |
}; | |
angular.extend(ctrl, isolatedFormCtrl); | |
} | |
}; | |
}]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment