Mastering Web Application

(Rick Simeone) #1

Building Advanced Directives


Using a directive controller in accordion

To enable the groups to communicate with each other the accordion directive
defines a directive controller, AccordionController. Each accordion-group
directive will require this controller.


The AccordionController directive controller will expose two methods, addGroup
and closeOthers, which the accordion-group directives will use to register
themselves as part of the accordion and to tell the other accordion-groups to close
when they are opened.


Unit testing a directive controller is very similar to testing an application
controller. See Chapter 2, Building and Testing, An Example App. Here is a test
for the closeOthers method:


describe('closeOthers', function() {
var group1, group2, group3;
beforeEach(function() {
ctrl.addGroup(group1 = $scope.$new());
ctrl.addGroup(group2 = $scope.$new());
ctrl.addGroup(group3 = $scope.$new());
group1.isOpen = group2.isOpen = group3.isOpen = true;
});
it('closes all groups other than the one passed', function() {
ctrl.closeOthers(group2);
expect(group1.isOpen).toBe(false);
expect(group2.isOpen).toBe(true);
expect(group3.isOpen).toBe(false);
});
});

We add three groups, which are all set to isOpen=true. After calling closeOthers
with group2 we test that group1 and group2 have isOpen set to false.


Here is the implementation of the AccordionController:


myModule.controller('AccordionController', ['$scope', '$attrs',
function ($scope, $attrs) {
this.groups = [];
this.closeOthers = function(openGroup) {
angular.forEach(this.groups, function (group) {
if ( group !== openGroup ) {
group.isOpen = false;
}
});
}
Free download pdf