Sharing data between controllers in AngularJS
I am using the following factory to fetch data from the API and store it in a local variable apiData.
app.factory('MyFactory', function($resource, $q) {
var apiData = [];
var service = {};
var resource = $resource('http://example.com/api/sampledata/');
service.getApiData=function() {
var itemsDefer=$q.defer();
if(apiData.length >0) {
itemsDefer.resolve(apiData);
}
else
{
resource.query({},function(data) {
apiData=data;
itemsDefer.resolve(data)
});
}
return itemsDefer.promise;
};
service.add=function(newItem){
if(apiData.length > 0){
apiData.push(newItem);
}
};
service.remove=function(itemToRemove){
if(apiData.length > 0){
apiData.splice(apiData.indexOf(itemToRemove), 1);
}
};
return service;
});
I am injecting apiData into my controllers like this:
$routeProvider
.when('/myview', {
templateUrl: 'views/myview.html',
controller: 'MyController',
resolve: {
queryset: function(MyFactory){
return MyFactory.getApiData();
}
}
})
app.controller('MyController', ['$scope', 'queryset',
function ($scope, queryset) {
$scope.queryset = queryset;
}
]);
Is this a good way to share a promise between different controllers, or is it better to use local storage or even cacheFactory?
How can I rewrite the MyFactory add () and remove () methods so that I can keep my shared variable in its current state (no need to update / create / delete the API)?
Thank!
source to share
You should use $ resource to get $ prom like: resource.query().$promise
instead $q.defer()
for cleaner code. Otherwise, you're good to go. You can use $cacheFactory
, but you can also use local var.
Isn't your shared variable in its current state with the current code?
I recommend that you take a look at ui-router and its nested and abstract views, where the allowed values ββare available to child controllers.
source to share