Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

How can I access variables within another function?

myApp.controller "RegistrationsController", ($scope, $location, $http, $modal)->
  $scope.open = () ->
    # move to global
    modalInstance = $modal.open(
      templateUrl: "/assets/angular/templates/registrations/_signup.html",
      controller: "ModalController"
    )
  $scope.cancel = ->
    modalInstance.dismiss('cancel')
  $scope.saveUser = () ->
    $scope.cancel()

From the code above I'm trying to dismiss the modalInstance (modal opened) via cancel function.

However, I guess I need to make modalInstance a global variable first?

share|improve this question

2 Answers 2

declare modalInstance outside of the functions. This will scope it to the whole controller.

myApp.controller "RegistrationsController", ($scope, $location, $http, $modal)->

  var modalInstance;

  $scope.open = () ->
    # move to global
    modalInstance = $modal.open(
      templateUrl: "/assets/angular/templates/registrations/_signup.html",
      controller: "ModalController"
    )
  $scope.cancel = ->
    modalInstance.dismiss('cancel')
  $scope.saveUser = () ->
    $scope.cancel()
share|improve this answer
1  
$scope.cancel without $scope.open may cause an error, but this seems like an edge case. –  Explosion Pills Aug 6 at 18:21

If you're trying to cancel from the ModalController then you can add inject the $modalInstance dependency like ...

.controller('ModalController', function($scope, $modalInstance) {
   $scope.cancel = function() {
     $modalInstance.dismiss('cancel');
   };
});

If you're trying to cancel it from anywhere else then you can share you're controller among other directives using require? Like

.directive('otherDirective', function() {
   return {
     require: 'RegistrationController',
     link: function(scope, el, attr, ctrl) {

     }
   }
});

Or you could use a service as mediator between other controllers, services, directive, what ever.

.service('mediator', function() {
   var modalInstance;

   this.modalInstance = function(instance) {
     if (instance) {
       modalInstance = instance;
     }

     return modalInstance;
   };
});

and then in your directives and controllers and what not, do something like...

.controller('SomeController', function(mediator) {

   this.cancel = function() {
     mediator.modalInstance().dismiss('cancel');
   });
});

You can amend for CoffeeScript ;)

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.