简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM