AngularJS > Scope

Isolating custom directive scope in AngularJS

How to isolate custom directive scope in AngularJS?

The custom directive we created before is good if we have one set of data to populate however in case we have more than one set of data to populate using the same directive, we will end us creating different controller for each set of data and calling the this cutom directive under each Controller scope in HTML.

To overcome this problem, we can use scope option while creating the directive. This help us setting up the directive scope based on attribute value defined in the directive.

In the below code snippet, focus on the <script> block where we have defined two properties of the $scope object.

In the directive, we have used scope option that let us set the scope of the directive based on its "info" attribute defined and the value of the $scope object is accessed using "People" object in this case.

    var app = angular.module("app", []);

    app.controller("CustomDirectiveIsolateScope", function ($scope) {
        $scope.Member = { username: 'Sheo', address: 'Hyderabad, India' };
        $scope.Employee = { username: 'Mannu', address: 'Bangaluru, USA' };

    app.directive("myDetails", function () {
        return {
            scope: {
                People: '=info'
            templateUrl: '/DemoSupportingFiles/angularjs-scope-isolate-details.html'

<div ng-app="app" ng-controller="CustomDirectiveIsolateScope">
    <my-details info="Member"></my-details>
    <my-details info="Employee"></my-details>

In this HTML code block, we have simply called the <my-details> directive with info attribute whose values are the name of the $scope property defined in the controller.


<table class="table">

In above template file, we have used "People" object defined in the scope option of the directive to access the property of the object for which that directive has been used (using the "info" attribute in the directive).


Isolating the scope of custom directive in AngularJS

 Views: 2637 | Post Order: 20

Write for us