Repository navigation
Expand file tree
/
Copy pathangularAMD.js
More file actions
383 lines (331 loc) · 14.5 KB
/
Copy pathangularAMD.js
File metadata and controls
383 lines (331 loc) · 14.5 KB
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
/*
angularAMD v<%= cvars.proj_version %>
(c) 2013-2014 Marcos Lin https://github.com/marcoslin/
License: MIT
*/
/*jslint node: true, vars: true, nomen: true */
/*globals define, angular */
define(function () {
var orig_angular,
alt_angular,
alternate_queue = [],
app_name,
app_injector,
app_cached_providers = {},
config_injector; // store the captured providerInjector (config-time injector)
// Private method to check if angularAMD has been initialized
function checkAngularAMDInitialized() {
if ( typeof orig_angular === 'undefined' ) {
throw Error("angularAMD not initialized. Need to call angularAMD.bootstrap(app) first.");
}
}
/**
* Create an alternate angular so that subsequent call to angular.module will queue up
* the module created for later processing via the .processQueue method.
*
* This delaying processing is needed as angular does not recognize any newly created
* module after angular.bootstrap has ran. The only way to add new objects to angular
* post bootstrap is using cached provider.
*
* Once the modules has been queued, processQueue would then use each module's _invokeQueue
* and _runBlock to recreate object using cached $provider. In essence, creating a duplicate
* object into the current ng-app. As result, if there are subsequent call to retrieve the
* module post processQueue, it would retrieve a module that is not integrated into the ng-app.
*
* Therefore, any subsequent angular.module call to retrieve the module created with alternate
* angular will return undefined.
*
*/
function setAlternateAngular() {
var alternateModules = {};
// This method cannot be called more than once
if (alt_angular) {
throw Error("setAlternateAngular can only be called once.");
} else {
alt_angular = {};
}
// Make sure that bootstrap has been called
checkAngularAMDInitialized();
// Createa a copy of orig_angular
orig_angular.extend(alt_angular, orig_angular);
// Custom version of angular.module used as cache
alt_angular.module = function (name, requires) {
if (typeof requires === "undefined") {
// Return undefined if module was created using the alt_angular
if (alternateModules.hasOwnProperty(name)) {
return undefined;
} else {
return orig_angular.module(name);
}
} else {
//console.log("alt_angular.module START for '" + name + "': ", arguments);
var orig_mod = orig_angular.module.apply(null, arguments),
item = { name: name, module: orig_mod};
alternate_queue.push(item);
alternateModules[name] = orig_mod;
return orig_mod;
}
};
window.angular = alt_angular;
};
// Constructor
function angularAMD() {}
/**
* Helper function to generate angular's $routeProvider.route. 'config' input param must be an object.
*
* Populate the resolve attribute using either 'controllerUrl' or 'controller'. If 'controllerUrl'
* is passed, it will attempt to load the Url using requirejs and remove the attribute from the config
* object. Otherwise, it will attempt to populate resolve by loading what's been passed in 'controller'.
* If neither is passed, resolve is not populated.
*
* This function works as a pass-through, meaning what ever is passed in as 'config' will be returned,
* except for 'controllerUrl' attribute.
*
*/
angularAMD.prototype.route = function (config) {
// Initialization not necessary to call this method.
var load_controller;
/*
If controllerUrl is provided, load the provided Url using requirejs. Otherwise,
attempt to load the controller using the controller name. In the later case,
controller name is expected to be defined as one of 'paths' in main.js.
*/
if ( config.hasOwnProperty("controllerUrl") ) {
load_controller = config.controllerUrl;
delete config.controllerUrl;
} else if (typeof config.controller === 'string') {
load_controller = config.controller;
}
// If controller needs to be loaded, append to the resolve property
if (load_controller) {
var resolve = config.resolve || {};
resolve['__load'] = ['$q', '$rootScope', function ($q, $rootScope) {
var defer = $q.defer();
require([load_controller], function () {
defer.resolve();
$rootScope.$apply();
});
return defer.promise;
}]
config.resolve = resolve;
}
return config;
};
/**
* Expose name of the app that has been bootstraped
*/
angularAMD.prototype.appname = function () {
checkAngularAMDInitialized();
return app_name;
};
/**
* Recreate the modules created by alternate angular in ng-app using cached $provider.
* As AMD loader does not guarantee the order of dependency in a require([...],...)
* clause, user must make sure that dependecies are clearly setup in shim in order
* for this to work.
*
* HACK ALERT:
* This method relay on inner working of angular.module code, and access _invokeQueue
* and _runBlock private variable. Must test carefully with each release of angular.
*/
angularAMD.prototype.processQueue = function () {
checkAngularAMDInitialized();
if (typeof alt_angular === 'undefined') {
throw Error("Alternate angular not set. Make sure that `enable_ngload` option has been set when calling angularAMD.bootstrap");
}
// Process alternate queue in FIFO fashion
while (alternate_queue.length) {
var item = alternate_queue.shift(),
invokeQueue = item.module._invokeQueue,
y;
// Setup the providers define in the module
for (y = 0; y < invokeQueue.length; y += 1) {
var q = invokeQueue[y],
provider = q[0],
method = q[1],
args = q[2];
if (app_cached_providers.hasOwnProperty(provider)) {
var cachedProvider;
if (provider === "$injector" && method === "invoke") {
cachedProvider = config_injector;
} else {
cachedProvider = app_cached_providers[provider];
}
//console.log("'" + item.name + "': applying " + provider + "." + method + " for args: ", args);
cachedProvider[method].apply(null, args);
} else {
console.error("'" + provider + "' not found!!!");
}
}
// Execute the run block of the module
if (item.module._runBlocks) {
angular.forEach(item.module._runBlocks, function processRunBlock(block) {
//console.log("'" + item.name + "': executing run block: ", run_block);
app_injector.invoke(block);
});
}
// How to remove the module???
orig_angular.module(item.name, [], orig_angular.noop);
}
};
/**
* Return cached app provider
*/
angularAMD.prototype.getCachedProvider = function (provider_name) {
checkAngularAMDInitialized();
// Hack used for unit testing that orig_angular has been captured
if (provider_name === "__orig_angular") {
return orig_angular;
} else if (provider_name === "__alt_angular") {
return alt_angular;
} else {
return app_cached_providers[provider_name];
}
};
/**
* Create inject function that uses cached $injector.
* Designed primarly to be used during unit testing.
*/
angularAMD.prototype.inject = function () {
checkAngularAMDInitialized();
return app_injector.invoke.apply(null, arguments);
};
/**
* Reset angularAMD for resuse
*/
angularAMD.prototype.reset = function () {
if (typeof orig_angular === 'undefined') {
return;
}
// Restore original angular instance
window.angular = orig_angular;
// Clear private variables
alt_angular = undefined;
alternate_queue = [];
app_name = undefined;
app_injector = undefined;
app_cached_providers = {};
// Clear original angular
orig_angular = undefined;
}
/**
* Initialization of angularAMD that bootstraps AngularJS. The objective is to cache the
* $provider and $injector from the app to be used later.
*
* enable_ngload:
*/
angularAMD.prototype.bootstrap = function (app, enable_ngload, elem) {
// Prevent bootstrap from being called multiple times
if (typeof orig_angular !== 'undefined') {
throw Error("bootstrap can only be called once.");
}
// Store reference to original angular which also used to check if bootstrap has take place.
orig_angular = angular;
if (typeof enable_ngload === 'undefined') {
enable_ngload = true;
}
elem = elem || document.documentElement;
// Cache provider needed
app.config(
['$controllerProvider', '$compileProvider', '$filterProvider', '$animateProvider', '$provide', '$injector', function (controllerProvider, compileProvider, filterProvider, animateProvider, provide, injector) {
// Cache Providers
config_injector = injector;
app_cached_providers = {
$controllerProvider: controllerProvider,
$compileProvider: compileProvider,
$filterProvider: filterProvider,
$animateProvider: animateProvider,
$provide: provide
};
// Create a app.register object
app.register = {
controller: controllerProvider.register,
directive: compileProvider.directive,
filter: filterProvider.register,
factory: provide.factory,
service: provide.service,
constant: provide.constant,
value: provide.value,
animation: angular.bind(animateProvider, animateProvider.register)
};
}]
);
// Get the injector for the app
app.run(['$injector', function ($injector) {
// $injector must be obtained in .run instead of .config
app_injector = $injector;
app_cached_providers.$injector = app_injector;
}]);
// Store the app name needed by .bootstrap function.
app_name = app.name;
// Bootstrap Angular
orig_angular.element(document).ready(function () {
orig_angular.bootstrap(elem, [app_name]);
});
// Replace angular.module
if (enable_ngload) {
//console.log("Setting alternate angular");
setAlternateAngular();
}
};
var mod = angular.module('amd', []);
mod.directive('amdRequire', [
// Angular services
'$compile',
// Factory
function($compile) {
return {
restrict: 'A',
priority: 1000,
scope: true,
replace: false,
transclude: true,
compile: function() {
return {
pre: function($scope, $element, attrs, ctrl, transclude) {
if (typeof attrs.amdBaseUrl !== 'undefined') {
if (attrs.amdBaseUrl.length && attrs.amdBaseUrl.charAt(attrs.amdBaseUrl.length - 1) != '/') {
// Add / to the end
attrs.amdBaseUrl += '/';
}
$scope.requireBaseUrl = attrs.amdBaseUrl;
}
var deps = attrs.amdRequire
.split(' ')
// Reduce to non-empty strings, append baseUrl
.reduce(function(pv, cv, i, a) {
var item = cv.trim();
if (item) {
var path;
if (item.charAt(0) == '.') {
// Apply relative pathing
while (item.indexOf('./') == 0) {
// Remove leading ./
item = item.substr(2);
}
path = ($scope.requireBaseUrl || '') + item;
} else {
path = item;
}
pv.push(path);
}
return pv;
}, []);
// Load dependencies
require(deps, function() {
// Compile transclude
$scope.$apply(function() {
transclude($scope, function (clone) {
$element.append(clone);
})
})
});
} // pre
} //return
} // compile
} // return
} // function
]);
// Create a new instance and return
return new angularAMD();
});