ANGUAR.JS: ISOLATING SCOPE IN DIRECTIVE

PROBLEM WITH DIRECTIVES AND SCOPE

Uraeus Millet
Jul 26, 2017 · 1 min read

In angular, a directive is a marker on an HTML DOM element that attaches a behavior to said DOM element. The con of attaching these behaviors to DOM elements is that the directives can only be used once in a specific scope. In the example below, each time you would want to re-use a directive, you would need to create a different controller for that directive.

angular.module('video-player')//use 1. setting video in a DOM element to an object
.controller('ListEntryCtrl', function($scope) {
$scope.video = {};
})
//use 2. setting video in a DOM element to an array
.controller('ListEntryCtrl', function($scope) {
$scope.video = [];
})
.directive(‘ListEntry’, function() {
return {
templateUrl: ‘src/templates/videoListEntry.html’,
bindToController: true,
controller: ‘ListEntryCtrl’,
controllerAs: ‘ctrl’,
};
});

IMPLEMENTING SOLUTION

By separating the scope inside a directive from the scope outside, you can map the outer scope to a directive’s inner scope. A directive’s scope option, object that contains a property for each isolate scope binding, allows this functionality. As seen below, a scope object within the directive has an attribute that defines what value you want bound to the directive.

.directive(‘videoListEntry’, function() {
return {
scope: {
//video attribute being bound to a value with the same name
video: ‘=’
},
templateUrl: ‘src/templates/videoListEntry.html’,
bindToController: true,
controller: ‘ListEntryCtrl’,
controllerAs: ‘ctrl’,
};
});
Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade