dcp3450
dcp3450

Reputation: 11187

In AngularJS, how can I call a directive inside a controller to perform a task?

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

Answers (1)

Agop
Agop

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

Related Questions