December 9, 2015

AngularJS - Defining Custom Directives Part III

After last 2 posts, we are now familiar with developing AngularJS custom directives. If you have not read old posts, I recommend to first take a look on these. In this post I will discuss the scope object inside the custom directive. By default, a directive have access to the parent scope. In the html markup where the directive is placed, it will get access to the scope object of the parent controller. For example in the following directive we can access an item property which is defined in the scope of the parent controller.
demoApp.directive('directiveUsingParentScope', function () {
    return {
        template: 'Item from parent controller: name = {{item.name}}, category = {{item.category}} '
    };
});
Directive Implementation:
Sorry for the long directive names I used in these examples, these are for demonstration purpose to make it more understandable.
This directive will render the name and category properties of item object defined in parent controller. But the limitation here is that the directive is totally depends on the parent controller and if you place directive some where outside of the scope of parent controller, it will not work as expected.
To make a directive more reusable and removing dependency on the parent scope we can isolate it. For this we have to define scope object in the directive declaration. In following example directive is defined with an empty object assigned to its scope, so this directive is no longer have direct access to the parent scope, and would not render the item's name and category.
demoApp.directive('directiveWithIsolateScope', function () {
    return {
        scope: {},
        template: 'Item from isolate scope: name = {{item.name}}, category = {{item.category}} '
    };
});
Directive Implementation:
But angular provides access to another object named $parent, through which we can access parent scope even inside an isolated directive. See this example:
demoApp.directive('directiveWithIsolateScopeAccessingParent', function () {
    return {
        scope: {},
        template: 'Item from isolate scope accessing parent scope: name = {{$parent.item.name}}, category = {{$parent.item.category}} '
    };
});
Directive Implementation:
This directive scope is isolated and have nothing to interact with outside world, but in the template content we are accessing the item property of the parent controller by using $parent object.

1 comment: