Skip to content

Commit fe3e8dd

Browse files
committed
feat(navbar): added new navbar directive
1 parent af3caf2 commit fe3e8dd

2 files changed

Lines changed: 81 additions & 0 deletions

File tree

src/directives/navbar.js

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
2+
angular.module('$strap.directives')
3+
4+
.directive('bsNavbar', ['$location', function($location) {
5+
'use strict';
6+
7+
return {
8+
restrict: 'A',
9+
link: function postLink($scope, element, attrs, controller) {
10+
// Watch for the $location
11+
$scope.$watch(function() {
12+
return $location.path();
13+
}, function(newValue, oldValue) {
14+
15+
element.find('li[data-match-route]').each(function(k, li) {
16+
var $li = angular.element(li),
17+
pattern = $li.data('match-route'),
18+
regexp = new RegExp('^' + pattern + '$', ["i"]);
19+
20+
if(regexp.test(newValue)) {
21+
$li.addClass('active');
22+
} else {
23+
$li.removeClass('active');
24+
}
25+
26+
});
27+
});
28+
}
29+
};
30+
}]);

test/unit/directives/navbarSpec.js

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
'use strict';
2+
3+
describe('navbar', function () {
4+
var scope, $sandbox, $compile, $timeout, $location;
5+
6+
beforeEach(module('$strap.directives'));
7+
8+
beforeEach(inject(function ($injector, $rootScope, _$compile_, _$timeout_, _$location_) {
9+
scope = $rootScope;
10+
$compile = _$compile_;
11+
$timeout = _$timeout_;
12+
$location = _$location_;
13+
14+
$sandbox = $('<div id="sandbox"></div>').appendTo($('body'));
15+
}));
16+
17+
afterEach(function() {
18+
$sandbox.remove();
19+
scope.$destroy();
20+
});
21+
22+
var templates = {
23+
'default': '<nav class="navbar" bs-navbar><ul class="nav"><li data-match-route="/network.*"><a href="#/network">Network</a></li><li data-match-route="/profile.*"><a href="#/profile">Profile</a></li></ul></nav>'
24+
};
25+
26+
function compileDirective(template) {
27+
template = template ? templates[template] : templates['default'];
28+
template = $(template).appendTo($sandbox);
29+
return $compile(template)(scope);
30+
}
31+
32+
// Tests
33+
34+
it('should toggle "active" class for you', function () {
35+
var elm = compileDirective();
36+
$location.path('/network'); scope.$digest();
37+
expect(elm.find('li:nth-child(1)').hasClass('active')).toBe(true);
38+
$location.path('/profile'); scope.$digest();
39+
expect(elm.find('li:nth-child(1)').hasClass('active')).toBe(false);
40+
expect(elm.find('li:nth-child(2)').hasClass('active')).toBe(true);
41+
});
42+
43+
it('should work with regular expressions', function () {
44+
var elm = compileDirective();
45+
$location.path('/network'); scope.$digest();
46+
expect(elm.find('li:first').hasClass('active')).toBe(true);
47+
$location.path('/network/config'); scope.$digest();
48+
expect(elm.find('li:first').hasClass('active')).toBe(true);
49+
});
50+
51+
});

0 commit comments

Comments
 (0)