I'm working on my first Angular.js application and I'm a bit confused. Currently I have two directives that both need the same data to build up the page. This data is loaded from an external api.
Now currently I have created this factory, which looks like:
(function() {
var app = angular.module('dataService', []);
app.factory('dataService', ['$http', function($http) {
var links = [];
return {
getMenu: function() {
if(links.length > 0) {
return links;
} else {
$http.get('http://localhost/server/api.php?ajax=true&action=getCats').success(function(data) {
return data;
})
}
}
}
}])
})();
But I'm rather confused how to use this service, obviously if there is a $http request, the return will never be called with the correct data.
In my directive I would use it like this:
(function() {
// Menu directive
var app = angular.module('menu', ['dataService']);
app.directive('menu', ['dataService', function(dataService) {
return {
restrict: 'E',
templateUrl: 'scripts/menu/menu.html',
controller: function() {
console.log(dataService.getMenu()); // Return 'undefined'
},
controllerAs: 'menuCtrl'
}
}])
})();