title: Call function from directive in $rootScope - AngularJS
body: <p><strong>What I want to do:</strong></p>
  
  <p>I'm trying to create a function within a directive that can be called from the <code>$rootScope</code>.</p>
  
  <hr>
  
  <p><strong>The Problem:</strong></p>
  
  <p>It seems to only be working on the last item in the DOM which has this directive. I'm guessing that what's happening is <code>rootScope.myFunction</code> gets overwritten each time this directive runs.</p>
  
  <hr>
  
  <p><strong>The Question:</strong></p>
  
  <p>How can I create one function in the <code>$rootScope</code> which, when called, runs the internal function for each directive instead of just the last one?</p>
  
  <hr>
  
  <p><strong>The Relevant Code:</strong></p>
  
  <pre><code>(function() {
    angular.module('home')
      .directive('closeBar', closeBar);
  
    closeBar.$inject = ['$rootScope', '$window'];
    function closeBar(rootScope, window) {
      return {
        scope: true,
        restrict: 'A',
        link: function(scope, element, attrs) {
  
          var myFunction = function() {
            // do stuff
          };
  
          myFunction();
  
          rootScope.myFunction = function() {
            myFunction();
          };
        }
      };
    }
  })();
  </code></pre>
  
  <p><strong>Then in a different script, I want to call:</strong></p>
  
  <pre><code>rootScope.myFunction();
  </code></pre>
  
  <hr>
  
  <p><strong>Note, I'm not allowed to share actual code from the project I'm working on so this is a more general question not tied to a specific use case.</strong></p>