I am currently developing a feature toggle directive, which requires a check to be performed in order to display content if the check is successful. I want the directive to replace itself with its content without creating a new child scope (so I'm trying not to transclude). However, when there are model bindings within the HTML of the directive, the binding is lost.
Below is an example of this issue with checkboxes (plunker). The 'normalChecked' checkbox maintains the binding, while the 'toggleChecked' checkbox does not. Can someone advise me on how to properly implement this functionality using an AngularJS directive?
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.11/angular.js"></script>
<script>
var app = angular.module('playground',[]);
var ToggleDirective = ['$timeout', function($timeout) {
return {
restrict: 'E',
link: function($scope, $element, $attr){
// timeout replicates http request
$timeout(function() {
console.log("here");
$element.replaceWith($element.children());
}, 100);
}
};
}];
app.directive('toggle', ToggleDirective);
</script>
</head>
<body ng-app="playground" ng-init="vm={toggleChecked:true, normalChecked:true};">
<toggle>
<input type="checkbox" ng-model="vm.toggleChecked">
</toggle><br/>
toggleChecked value = {{vm.toggleChecked}}<br><br><br><br><br><br><br><br>
<input type="checkbox" ng-model="vm.normalChecked"><br>
normalChecked value = {{vm.normalChecked}}
</body>
</html>
EDIT The actual directive code makes an HTTP service call to determine if the user has access to a feature. If they do have access, it replaces the toggle element with its contents as shown above. If not, it removes the element from the DOM.