Building Advanced Directives
<div if="model.show" ng-init="model.count=model.count+1">
Shown {{model.count}} times
</div>
</body>
Here, each time the button is clicked the value of model.show is toggled between
true and false. To show that the DOM element is being removed and reinserted
on each toggle, we are incrementing model.count.
In the unit tests we will need to test that the DOM element is actually added and
removed correctly:
it('creates or removes the element as the if condition changes',
function () {
element = $compile(
'<div><div if="someVar"></div></div>')(scope);
scope.$apply('someVar = true');
expect(element.children().length).toBe(1);
scope.$apply('someVar = false');
expect(element.children().length).toBe(0);
scope.$apply('someVar = true');
expect(element.children().length).toBe(1);
});
Here we check that the number of children on our container element increases or
decreases as the expression toggles between true and false.
Note that we need to wrap the element that contains the if directive
in a div because our directive will use jqLite.after() to insert it
into the DOM, which requires that the element has a parent.
Let's take a look at how to implement this directive:
myModule.directive('if', function () {
return {
transclude: 'element',
priority: 500,
compile: function (element, attr, transclude) {
return function postLink(scope, element, attr) {
var childElement, childScope;
scope.$watch(attr['if'], function (newValue) {
if (childElement) {