Himmators
Himmators

Reputation: 15026

Call a function in a angular-controller from outside of the controller?

I have a lightbox-dierective and controller that looks like this:

directive('modalDialog', function() {
  return {
    restrict: 'E',
    scope: {
      show: '='
    },
    replace: true, // Replace with the template below
    transclude: true, // we want to insert custom content inside the directive
    template: '<div class="ng-modal" ng-show="show"><div class="ng-modal-overlay" ng-click="hideModal()"></div><div class="ng-modal-dialog" ng-style="dialogStyle"><div class="ng-modal-dialog-content" ng-transclude><div class="ng-modal-close" ng-click="hideModal()">X</div></div></div></div>'
  };
}).controller('Lightbox', function($scope) {
  $scope.modalShown = false;
  $scope.toggleModal = function() {
    $scope.modalShown = !$scope.modalShown;
  };
});

Here is the desierd html, what I need is to open the secon ligthbox from withing the first one:

<div ng-controller="Lightbox">
     <span ng-mousedown='toggleModal()'>Open lightbox one</span>
    <modal-dialog show='modalShown'>
      <h2>One lightbox <span ng-mousedown='toggleModal()'>Open lightbox two</span></h2>
    </modal-dialog>
</div>

<div ng-controller="Lightbox">
    <span ng-mousedown='toggleModal()'>Open lightbox one</span>

    <modal-dialog show='modalShown'>
      <h2>another lightbox</h2>
    </modal-dialog>
</div>

For most cases it works great! I use it in several occations throughout the site, with diffrent lightboxes and different content.

I have now come across a case, where I need to call one of the lightboxes from outside of the controller. Can this be achieved and in that case how do I reference the right lightbox?

Upvotes: 0

Views: 279

Answers (1)

Stav Geffen
Stav Geffen

Reputation: 308

I'd extend that setting to an object

var modalSet = {
  shown: false,
  toggle: function(){ modalSet.shown = !modalSet.shown }
}

Then put it on your main controller (the one with ngApp attribute) and have your entire scope modaleble.

Also, directives do have a controller option, but since only one modal is gonna show up at any given time, you might not want to re-create a controller for every new instance.

Upon re-reading your question: Where is it exactly -> "outside of the controller"?

Upvotes: 1

Related Questions