-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathxl-activetabs.js
73 lines (66 loc) · 3.72 KB
/
xl-activetabs.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
'use strict';
angular.module('xl-activetabs', [])
.directive('xlDetectActiveTab', ['$location',
function($location) {
return {
link: function postLink(scope, element, attrs) {
scope.$on("$routeChangeSuccess", function(event, current, previous) {
/*
Designed for full re-usability at any path, any level, by using data from attrs.
Declare like this: <li class="nav_tab"><a href="#/home" active-tab="1">HOME</a></li>
*/
// This var grabs the tab-level off the attribute, or defaults to 1
var pathLevel = attrs.detectActiveTab || 1,
// This var finds what the path is at the level specified
pathToCheck = $location.path().split('/')[pathLevel] || "current $location.path doesn't reach this level",
// This var finds grabs the same level of the href attribute
tabLink = attrs.href.split('/')[pathLevel] || "href doesn't include this level";
console.log(pathToCheck);
console.log(tabLink);
// Above, we use the logical 'or' operator to provide a default value in cases
// where 'undefined' would otherwise be returned.
// This prevents cases where undefined===undefined, possibly causing multiple tabs to be 'active'.
// now compare the two:
if (pathToCheck === tabLink) {
element.addClass("active");
} else {
element.removeClass("active");
}
});
}
};
}
]);
angular.module('xl-activetabs')
.directive('xlFindActiveTab', ['$location',
function($location) {
return {
link: function postLink(scope, element, attrs) {
scope.$on("$routeChangeSuccess", function(event, current, previous) {
/* designed for full re-usability at any path, any level, by using data from attrs
declare like this:
<nav show-active-tab="1">
<a href="#/home">HOME</a>
</nav>
*/
// this var grabs the tab-level off the attribute, or defaults to 1
var pathLevel = attrs.findActiveTab || 1,
// this var finds what the $location.path is at the level specified
pathToCheck = $location.path().split('/')[pathLevel] || "current $location.path doesn't reach this level";
// now, iterate the children. Ideally, child elements should all be <a>'s.
angular.forEach(element.children(), function(item) {
var specimen = angular.element(item),
// find each item's matching level on the href attribute
tabLink = specimen.attr('href').split('/')[pathLevel] || "href doesn't include this level";
// now compare the item to the current $location:
if (pathToCheck === tabLink) {
specimen.addClass("active");
} else {
specimen.removeClass("active");
}
})
});
}
};
}
]);