Reputation: 18125
I have a service for handle the menu of my application I dont want call from any controller, where is the best place for call my service
my service has a register
method
// sample
menuService.register({name: "Person", label: "Person", url: "/persons"});
menuService.register({name: "Company", label: "Companies", url: "/companies"});
is defined like
app.service('MenuService', ['$rootScope', function($r) { /*...*/ }
Note: my service $rootScope.$emit
and is listen by a directive and depends of $rootScope
and $location
Upvotes: 0
Views: 706
Reputation: 4611
you should use .run
block for that, but keep in mind you cannot inject .provider
to run block
yourApp.run(function ($rootScope, $location) {
// your code goes herer
});
Run blocks are the closest thing in Angular to the main method. A run block is the code which needs to run to kickstart the application. It is executed after all of the services have been configured and the injector has been created. Run blocks typically contain code which is hard to unit-test, and for this reason should be declared in isolated modules, so that they can be ignored in the unit-tests.
Upvotes: 1
Reputation: 26870
You could expose the menus as a model in the MenuService
.
app.service('MenuService', ['$rootScope', function($r) {
var svcModel = {
menus: []
};
var registerMenu = function(menu) {
svcModel.menus.push(menu);
};
/*...*/
return {
model: svcModel,
register: registerMenu
/*...*/
};
}
And then access that model directly on the directive:
app.directive('menuDirective', ['MenuService', function(MenuService) {
return {
/*...*/
link: function(scope, element, attrs) {
/*...*/
scope.menus = MenuService.model.menus;
}
}]);
Upvotes: 0