ANGUAR.JS: ISOLATING SCOPE IN DIRECTIVE

PROBLEM WITH DIRECTIVES AND SCOPE

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’,
};
});
Like what you read? Give Uraeus Millet a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.