Isolate scope
Often, you will find that the inheritance of a directive's parent scope is undesirable somewhere in your application. To prevent inheritance and to create a blank slate scope for the directive, isolate scope is utilized.
Getting ready
Suppose that you begin with the following skeleton application:
(index.html - uncompiled) <div ng-app="myApp"> <div ng-controller="MainCtrl"> <my-directive> Stuff inside </my-directive> </div> <script type="text/ng-template" id="my-directive.html"> <div> <p>Directive template</p> <p>Scope from {{origin}}</p> <p>Overwritten? {{overwrite}}</p> </div> </script> </div> (app.js) angular.module('myApp', []) .controller('MainCtrl', function ($scope) { $scope.overwrite = false; $scope.origin = 'parent controller'; });
How to do it…
Assign an isolate scope to the directive with an empty object literal, as follows:
(app.js) .directive('myDirective', function() { return { templateUrl: 'my-directive.html', replace: true, scope: {}, link: function (scope) { scope.overwrite = !!scope.origin; scope.origin = 'link function'; } }; });
This will compile into the following:
(index.html – compiled) <div> <p>Directive template</p> <p>Scope from link function</p> <p>Overwritten? false</p> </div>
Tip
JSFiddle: http://jsfiddle.net/msfrisbie/a2vmuhd3/
How it works…
The directive creates its own scope and performs the modifications on the scope instead of performing them inside the link
function. The parent scope is unchanged and obscured from inside the directive's link
function.
See also
- The Directive scope inheritance recipe goes over the basics that involve carrying the parent scope through a directive
- The Directive templating recipe examines how a directive can apply an external scope to an interpolated template
- The Directive transclusion recipe demonstrates how a directive handles the application of a scope to the interpolated existing nested content