-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathangular-namespacer.js
80 lines (65 loc) · 1.87 KB
/
angular-namespacer.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
74
75
76
77
78
79
80
(function (angular) {
'use strict';
var slice = Array.prototype.slice;
var angularModule = angular.bind(angular, angular.module);
var defaults = {
methods: 'constant factory provider service value'.split(' '),
delimiter: '.',
camelCase: false
};
/**
* Attempts to read default configurations set by user
* @return {Object}
*/
function getUserOptions () {
try {
return angular.injector(['ns']).get('config');
}
catch (e) {
return {};
}
}
/**
* Gets namespacing options for current module
* @param {Function} callback
* @return {Object}
*/
function getNsOptions (instanceOptions) {
var options = angular.copy(defaults);
angular.extend(options, getUserOptions(), instanceOptions);
return options;
}
function capitalize (str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
/**
* Monkey patches the instance methods to apply namespace
* @param {Object} angular module
* @param {Object} namespace options
*/
function monkeyPatch (instance, options) {
angular.forEach(options.methods, function (method) {
var instanceMethod = instance[method];
instance[method] = function () {
var args = slice.call(arguments);
if (options.camelCase) {
args[0] = instance.name + capitalize(args[0]);
} else {
args[0] = [instance.name, args[0]].join(options.delimiter);
}
return instanceMethod.apply(instance, args);
};
});
}
/**
* Decorates angular module instance to allow for namespaces
*/
angular.module = function (moduleName, requires, configFn) {
var instance = angularModule(moduleName, requires, configFn);
instance.namespace = function (options) {
monkeyPatch(instance, getNsOptions(options || {}));
return instance;
};
return instance;
};
}(this.angular));