AngularJS: Restricting and isolating the scope of a Directive

Hi Guys,

Sharing with you an example how to isolate and restrict the scope of Directive

Isolating the Scope of a Directive
A custom directive can only use it once within a given scope. What we want to be able to do is separate the scope inside a directive from the scope outside, and then map the outer scope to a directive's inner scope. We can do this by creating what we call an isolate scope. To do this, we can use a directive's scope option

Restricting the Scope of a Directive
When you create a directive, it is restricted to attribute and elements only by default. In order to create directives that are triggered by class name, you need to use the restrict option.

The restrict option is typically set to:
  • 'A' - only matches attribute name
  • 'E' - only matches element name
  • 'C' - only matches class name
These restrictions can all be combined as needed:
  • 'AEC' - matches either attribute or element or class name

In below example I have used element ('E') restrict option and scope "=".

index.html
<html ng-app="simpleDirective">
<head>
<script src="angular.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<div ng-controller="MyController">
  <my-customer info="customer"></my-customer>
</div>
</body>
</html>
app.js
var app = angular.module('simpleDirective', []);

app.controller('MyController', ['$scope', function($scope) {
  $scope.customer = [{
    name: 'Alex',
    quantity: '70'
  },{
    name: 'Alisha',
    quantity: '100'
  },{
    name: 'Shankar',
    quantity: '50'
  }];
}]);

app.directive('myCustomer', function() {
  return {
   restrict:"E",
   scope:{
    customerInfo:"=info"
   },
   templateUrl: "table.html"
  };
});
table.html
<table ng-repeat="obj in customerInfo">
 <tr>
  <td>
   {{obj.name}}
  </td>
  <td>
   {{obj.quantity}}
  </td>
 </tr>
</table>

1. How restriction of scope works?
The html $compile reads restrict option and compiles and create DOM element as instructed. So if directive is restricted to element and anyone try to use as attribute or class, the binding will fail to create directive.

2. How isolation of scope works?
myCustomer directive has scope name customerInfo which is the current scope to the directive so customerInfo will be accessible in table.html.
Now the question is how does customerInfo get model object?
So it is done by using "=info". Customer model is mapped in MyController which is injected in info attribute in index.html. The "info" attribute holds customer model object which the latter mapped in myCustomer directive scope.

Hope this might help you to understand restriction and isolation of scope.

Good Day :)

Post a Comment

0 Comments