// example 1
angular.module('app', [])
.controller('mainCtrl', ['factoryOne', '$rootscope', function
(factoryOne, $rootscope) {
factoryOne.get('url1');
var data = $rootscope.data;
}])
.factory('factoryOne', ['$http', '$rootscope', function ($http,
$rootscope) {
var urls = {
url1: 'http://url1',
url2: 'http://url2',
//...
};
return {
get: function (url) {
if (!$rootScope.data[url]) {
$http.get(urls[url]).then(function(response) {
$rootScope.data[url] = response;
});
}
}
};
}]);
// example 2
angular.module('app', [])
.controller('mainCtrl', ['factoryTwo', function (factoryTwo) {
factoryTwo.get('url1');
var data = factoryTwo.data;
}])
.factory('factoryTwo', ['$http', function ($http) {
var urls = {
url1: 'http://url1',
url2: 'http://url2',
//...
};
var data = {};
return {
data: data,
get: function (url) {
if (!data[url]) {
$http.get(urls[url]).then(function(response) {
data[url] = response;
});
}
}
};
}]);
Hello,
I am trying to build a website with angular. At this website if have some
routes which require some different calls to an API. Now I search a
flexible way to make this calls and inject the data to the different
controller but don't load the data twice if 2 routes need the same api.
I had 2 ideas to solve this problem:
1. Creating a factory/service which loads the data into the $rootscope
after checking if the data was already loaded.
(that's a possible way but doesn't look right in my eyes)
2. Creating a factory/service which loads the data into the
factory/service after checking [...]
(the problem is that Angular don't update the data automatically into
the controller)
Is there any way to solve this problem in a smart way?
--
You received this message because you are subscribed to the Google Groups
"AngularJS" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/angular.
For more options, visit https://groups.google.com/d/optout.