var app = angular.module('plunker', []);
app.directive('if', [function () {
return {
transclude: 'element',
priority: 500,
compile: function (element, attr, transclude) {
return function (scope, element, attr) {
var childElement;
var childScope;
scope.$watch(attr['if'], function (newValue) {
// Remove the element and scope as we are going to (re)create them now.
if (childElement) {
childElement.remove();
childElement = undefined;
childScope.$destroy();
childScope = undefined;
}
// If the attribute evaluates to true then we need to clone the transcluded DOM with a new scope
if (newValue) {
childScope = scope.$new();
childElement = transclude(childScope, function(clone) {
element.after(clone);
});
}
});
};
}
};
}]);
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js@1.3.x" src="https://code.angularjs.org/1.3.15/angular.js" data-semver="1.3.15"></script>
<script src="app.js"></script>
</head>
<body ng-init="model= {show: true, count: 0}">
<button ng-click="model.show = !model.show">Toggle Div</button>
<div if="model.show" ng-init="model.count=model.count+1">
Shown {{model.count}} times
</div>
</body>
</html>
/* Put your css in here */