Building Your Own Directives
Writing a button directive
All the buttons in our application should be styled as a Bootstrap CSS button. Instead
of having to remember to add class="btn" to every button, we can add a button
directive to do this for us. The unit tests for this look like:
describe('button directive', function () {
var $compile, $rootScope;
beforeEach(module('directives.button'));
beforeEach(inject(function(_$compile_, _$rootScope_) {
$compile = _$compile_;
$rootScope = _$rootScope_;
}));
it('adds a "btn" class to the button element', function() {
var element = $compile('<button></button>')($rootScope);
expect(element.hasClass('btn')).toBe(true);
});
});
});
We load the module, create a button, and check that it has the correct CSS class.
Remember that the injector ignores a pair of underscores (for example,
_$compile_) surrounding the parameter name. This allows us to copy
the injected services into variables with the correct name for use later
(for example, $compile = _$compile_).
Further any button with type="submit" should automatically be styled as a primary
button and it would be nice to set the size of the button through an attribute size. We
would like to simply write:
<button type="submit" size="large">Submit</button>
We would create unit tests like this:
it('adds size classes correctly', function() {
var element = $compile('<button size="large"></button>')
($rootScope);
expect(element.hasClass('btn-large')).toBe(true);
});
it('adds primary class to submit buttons', function() {
var element = $compile('<button type="submit"></button>')
($rootScope);
expect(element.hasClass('btn-primary')).toBe(true);
});