Is it possible to determine the currently active controllers? With active I don't mean loaded, but used in the current view hierarchy.
What I want to do is update a global keyboard shortcut list, depending on what controllers are currently active (which keyboard shortcuts are available for the current view).
I think one way to do this is using a service to store the name of the active controller or even the menu you want to display. Every time the view changes the controller will be executed and so you could run a function to update the service.
Here is a fiddle with a similar situation, I am using a Menu service that stores different menus for each view, the service has a setMenu() and getMenu(), every time a controller is executed it informs the service which menu is to be activated and whenever i call getMenu() it will return the active menu.
/* Services */
app.factory('Menu', function () {
var activeMenu;
var menu = {
home: '<button>A</button><button>B</button>',
list: '<button>C</button><button>D</button>',
settings: '<button>E</button><button>F</button>',
}
function setMenu(name) {
activeMenu = name;
}
function getActiveMenu() {
return menu[activeMenu];
}
return {
setMenu: setMenu,
getMenu : getActiveMenu
}
});
/* Controllers */
function HomeCtrl($scope, Menu) {
Menu.setMenu('home');
$scope.menu = Menu.getMenu();
}
function ListCtrl($scope, Menu) {
Menu.setMenu('list');
$scope.menu = Menu.getMenu();
}
function SettingsCtrl($scope, Menu) {
Menu.setMenu('settings');
$scope.menu = Menu.getMenu();
}
Yes we can.
There two resources on the web that will help us to solve this :
So, as you can notice, the question is anwserable only if it is : "is there a mean to know what controllers have an active scope", because there are no mean to know anything about the controller lifecycle itself.
First, define a RegisterableCtrl as follow (I didn't check the code, it is just to have an idea of how to achieve it)
myApp.controller("RegisterableCtrl", function ($scope, ActiveScopesServices) {
// each time a scope is active this constructor will be called
ActiveScopesServices.add(...);
// each time a scope is removed this event receiver will be called
$scope.$on('$destroy', function dismiss() {
ActiveScopesServices.remove(...);
});
});
Then, for each Controller of your app, inject the ability to register, like this :
myApp.controller("MyCtrl2", function ($scope, ActiveScopesServices) {
//inject registrable behaviour
$injector.invoke(function ($controller) { $controller('RegisterableCtrl', {$scope: $scope});
//continue to normal code of your controller
});
We can do better because here we have to invoke the $injector at the beginning of each custom controller. So if you want to go further have a look at what is called "AOP", aspect oriented programming. There is already such an attempt here :
https://github.com/mgechev/angular-aop
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With