-
Notifications
You must be signed in to change notification settings - Fork 7
/
crumble.js
71 lines (60 loc) · 1.85 KB
/
crumble.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
!function() {
'use strict';
var ERR_NO_ROUTE = 'Could not find matching route definition for path ';
var ERR_NO_LABEL = 'Could not find property "label" of type "String" in route'
+ ' definition for path ';
var ERR_NO_PATH = 'No path given to getParent()';
function bakery($location, $route, $interpolate) {
var crumble = {
trail: [],
context: {},
};
crumble.update = function(context) {
crumble.context = context || crumble.context;
crumble.trail = build($location.path());
};
crumble.getParent = function(path) {
if (!path) {
throw new Error(ERR_NO_PATH);
}
return path.replace(/[^\/]*\/?$/, '');
};
crumble.getCrumb = function(path) {
var route = crumble.getRoute(path);
if (!route) {
throw new Error(ERR_NO_ROUTE + JSON.stringify(path));
}
if (!angular.isString(route.label)) {
throw new Error(ERR_NO_LABEL + JSON.stringify(path));
}
return {
path: $interpolate(path)(crumble.context),
label: $interpolate(route.label)(crumble.context),
};
};
crumble.getRoute = function(path) {
var route = find($route.routes, function(route) {
return route.regexp && route.regexp.test(path);
});
return (route && route.redirectTo)
? $route.routes[route.redirectTo]
: route;
};
function build(path) {
return path
? build(crumble.getParent(path)).concat(crumble.getCrumb(path))
: [];
}
function find(obj, fn, thisArg) {
for (var key in obj) {
if (obj.hasOwnProperty(key) && fn.call(thisArg, obj[key], key, obj)) {
return obj[key];
}
}
}
return crumble;
}
angular
.module('crumble', ['ngRoute'])
.factory('crumble', ['$location', '$route', '$interpolate', bakery]);
}();