I created a custom directive for switching elements from the DOM. This is similar to ng-show, but with the actual manipulation of dom, not using styles. For reasons beyond the scope of this question, I cannot use ng-show.
angular.module('myApp')
.directive('daKeep', [
function () {
function link($scope, element, attributes) {
var cacheElement, insertionElement;
var expression = attributes.daKeep;
function removeElement() {
if (insertionElement === undefined) {
insertionElement = element.prev();
cacheElement = element;
element.remove();
}
}
function addElement() {
if (insertionElement !== undefined) {
insertionElement.after(cacheElement);
insertionElement = undefined;
}
}
if (!$scope.$eval(expression)) {
removeElement();
}
$scope.$watch(expression, function (newValue, oldValue) {
if (newValue === oldValue) {
return;
}
if (newValue) {
addElement();
} else {
removeElement();
}
});
}
return ({
link: link,
restrict: "A"
});
}
]);
It worked fine for my needs, but when I used it on the container element that housed some of the [radio] input buttons, the bindings for my radio buttons were broken when the element was added back.
Is there any way to fix my directive so that the bindings do not break?
Example here: plunker