Angular Calling Modal Open function from one controller to another

元气小坏坏 提交于 2019-12-06 08:27:12

问题


I have a Modal window in my header, with a Click event link in my header to open and close the Modal Window...and this works fine. I.e.

<div class="header" ng-controller="headerCtrl">
...
          <li><a href ng-click="open()">Report an Issue</a></li>
...
</div>

and then my controllers

 .controller('headerCtrl', ['$location', '$scope', '$log', '$modal', function ($location, $scope, $log, $modal) {
    'use strict';
    (function () {// init
      $scope.open = function (size) {
        var modalInstance = $modal.open({
          templateUrl: 'views/help/supportModalContent.html',
          controller: 'supportInstanceCtrl'
        });
      };
    })();
  }])

  .controller('supportInstanceCtrl', ['$location', '$scope', '$log', '$modalInstance','$state', function ($location, $scope, $log, $modalInstance,$state) {
    'use strict';
    (function () {// init
      $scope.ok = function () {
        $modalInstance.close($scope.selected.item);
      };
      $scope.isCollapsed = false;
      $scope.message_sent = false;
    })();

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

    $scope.faq = function () {
      $modalInstance.close('cancel');
      $state.go('faq');
    };

    $scope.help = function () {
      $modalInstance.close('cancel');
      $state.go('help');
    };

    $scope.send = function () {
      $scope.isCollapsed = true;
      $scope.message_sent = true;
    };
  }])

The problem is now in one of my main content view, I now also have a link below which says something click here for support. And I want to open the same modal window again. So I did this

  .controller('noResultCtrl', ['$location','$scope','$log','search','$state','$modal',function ($location,$scope,$log,search,$state,$modal) {
    'use strict';
    $scope.open = function (size) {
      var modalInstance = $modal.open({
        templateUrl: 'views/help/supportModalContent.html',
        controller: 'supportInstanceCtrl'
      });
    };
  }])

And it works but is there a better way rather having to put this same logic in every controllers I want to call the same Modal Window in the header ?


回答1:


app.service('modalProvider',['$modal', function ($modal){

this.openPopupModal= function() {
var modalInstance = $modal.open({
          templateUrl: 'views/help/supportModalContent.html',
          controller: 'supportInstanceCtrl'
        });
}

Include this service in your controllers, and call openPopupModal method.For example:

.controller('noResultCtrl', ['$location','$scope','$log','search','$state','modalProvider',function ($location,$scope,$log,search,$state,modalProvider) {
    'use strict';
modalProvider.openPopupModal();


来源:https://stackoverflow.com/questions/28086854/angular-calling-modal-open-function-from-one-controller-to-another

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!