Commit | Line | Data |
---|---|---|
a2dc0f82 TO |
1 | // crmResource: Given a templateUrl "~/mymodule/myfile.html", load the matching HTML. |
2 | // This implementation loads all partials and strings in one batch. | |
3 | (function(angular, $, _) { | |
4 | angular.module('crmResource', []); | |
5 | ||
6 | angular.module('crmResource').factory('crmResource', function($q, $http) { | |
7 | var deferreds = {}; // null|object; deferreds[url][idx] = Deferred; | |
8 | var templates = null; // null|object; templates[url] = HTML; | |
9 | ||
10 | var notify = function notify() { | |
11 | var oldDfrds = deferreds; | |
12 | deferreds = null; | |
13 | ||
14 | angular.forEach(oldDfrds, function(dfrs, url) { | |
15 | if (templates[url]) { | |
16 | angular.forEach(dfrs, function(dfr) { | |
17 | dfr.resolve({ | |
18 | status: 200, | |
19 | headers: function(name) { | |
20 | var headers = {'Content-type': 'text/html'}; | |
21 | return name ? headers[name] : headers; | |
22 | }, | |
23 | data: templates[url] | |
24 | }); | |
25 | }); | |
26 | } | |
27 | else { | |
28 | angular.forEach(dfrs, function(dfr) { | |
29 | dfr.reject({status: 500}); // FIXME | |
30 | }); | |
31 | } | |
32 | }); | |
33 | }; | |
34 | ||
466e4b29 | 35 | var moduleUrl = CRM.angular.bundleUrl; |
a2dc0f82 TO |
36 | $http.get(moduleUrl) |
37 | .success(function httpSuccess(data) { | |
38 | templates = []; | |
39 | angular.forEach(data, function(module) { | |
40 | if (module.partials) { | |
41 | angular.extend(templates, module.partials); | |
42 | } | |
43 | if (module.strings) { | |
e3d90d6c | 44 | CRM.addStrings(module.domain, module.strings); |
a2dc0f82 TO |
45 | } |
46 | }); | |
47 | notify(); | |
48 | }) | |
49 | .error(function httpError() { | |
50 | templates = []; | |
51 | notify(); | |
52 | }); | |
53 | ||
54 | return { | |
55 | // @return string|Promise<string> | |
56 | getUrl: function getUrl(url) { | |
57 | if (templates !== null) { | |
58 | return templates[url]; | |
59 | } | |
60 | else { | |
61 | var deferred = $q.defer(); | |
62 | if (!deferreds[url]) { | |
63 | deferreds[url] = []; | |
64 | } | |
65 | deferreds[url].push(deferred); | |
66 | return deferred.promise; | |
67 | } | |
68 | } | |
69 | }; | |
70 | }); | |
71 | ||
72 | angular.module('crmResource').config(function($provide) { | |
73 | $provide.decorator('$templateCache', function($delegate, $http, $q, crmResource) { | |
74 | var origGet = $delegate.get; | |
75 | var urlPat = /^~\//; | |
76 | $delegate.get = function(url) { | |
77 | if (urlPat.test(url)) { | |
78 | return crmResource.getUrl(url); | |
79 | } | |
80 | else { | |
81 | return origGet.call(this, url); | |
82 | } | |
83 | }; | |
84 | return $delegate; | |
85 | }); | |
86 | }); | |
87 | ||
88 | })(angular, CRM.$, CRM._); |