访问AngularJS中另一个函数的局部变量

时间:2014-08-06 18:16:45

标签: javascript angularjs

如何在另一个函数中访问变量?

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

从上面的代码我试图通过modalInstance函数解除cancel(模态打开)。

但是,我想我需要先将modalInstance作为全局变量吗?

2 个答案:

答案 0 :(得分:1)

在函数之外声明modalInstance。这将把它的范围扩展到整个控制器。

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

答案 1 :(得分:1)

如果您尝试从ModalController取消,那么您可以添加注入$modalInstance依赖项,例如......

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

如果您尝试从其他任何地方取消它,那么您可以使用require在其他指令中共享您的控制器吗?喜欢

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

     }
   }
});

或者你可以使用服务作为其他控制器,服务,指令之间的中介。

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

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

     return modalInstance;
   };
});

然后在你的指令和控制器中,什么不是,做一些像......

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

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

您可以修改CoffeeScript;)