0

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?

2 Answers 2

1

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()
Sign up to request clarification or add additional context in comments.

1 Comment

$scope.cancel without $scope.open may cause an error, but this seems like an edge case.
1

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 ;)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.