What you need is properly a service:
.factory('DataLayer', ['$http',
function($http) {
var factory = {};
var locations;
factory.getLocations = function(success) {
if(locations){
success(locations);
return;
}
$http.get('locations/locations.json').success(function(data) {
locations = data;
success(locations);
});
};
return factory;
}
]);
The locations
would be cached in the service which worked as singleton model. This is the right way to fetch data.
Use this service DataLayer
in your controller and directive is ok as following:
appControllers.controller('dummyCtrl', function ($scope, DataLayer) {
DataLayer.getLocations(function(data){
$scope.locations = data;
});
});
.directive('map', function(DataLayer) {
return {
restrict: 'E',
replace: true,
template: '<div></div>',
link: function(scope, element, attrs) {
DataLayer.getLocations(function(data) {
angular.forEach(data, function(location, key){
//do something
});
});
}
};
});