Reputation: 11187
I have a controller that performs some DB calls and loads content into my $scope
accordingly. Everything works perfect. When the calls are complete I run some JS inside the controller in a call back to adjust the height and other attributes of my application. Unfortunately, I'm running this JS in multiple controllers.
I'd like to place the script into a directive so I can run the directive in the controllers callback and only have the JS live in one spot. Other than this being "the correct way" it will make upkeep much easier.
Upvotes: 0
Views: 59
Reputation: 1917
When sharing code between several controllers, use a service.
Example code from AngularJS docs:
angular.
module('myServiceModule', []).
controller('MyController', ['$scope','notify', function ($scope, notify) {
$scope.callNotify = function(msg) {
notify(msg);
};
}]).
factory('notify', ['$window', function(win) {
var msgs = [];
return function(msg) {
msgs.push(msg);
if (msgs.length == 3) {
win.alert(msgs.join("\n"));
msgs = [];
}
};
}]);
Directives are for use in the HTML, not for scripting within the controllers.
Upvotes: 1