【问题标题】:angularjs modal service broadcast and on issueangularjs模态服务广播和问题
【发布时间】:2017-08-09 19:58:26
【问题描述】:

我正在使用angular-modal-service 库。我的逻辑是:当模态打开时,它运行来自SomeService 的函数,以及从SomeService 到模态控制器的$rootScope.$broadcast,这样我就可以将资源从服务发送到我的模态控制器。但是,它不会触发。请帮我弄清楚我错过了什么。谢谢。

**服务:**

angular.module('ng-laravel').service('SomeService', function($rootScope, Restangular, CacheFactory, $http) {
     this.testFunction = function() {
        console.log("from service");
        $rootScope.$broadcast('event', {success:'success'});
     };
}

**控制器:**

$scope.show = function(customer_id) {

        ModalService.showModal({
            templateUrl: 'modal.html',
            inputs: {
                customer_id: customer_id
            },
            scope: $scope,
            controller: function($scope, close) {
                $scope.customer_id = customer_id;
                $scope.close = function(result) {
                    close(result, 500); // close, but give 500ms for bootstrap to animate
                };
                $scope.$on('event', function(event, data){
                    alert('yes');
                    console.log('from modal controller');
                });
            }
        }).then(function(modal) {
        SomeService.testFunction(customer_id, tour_id);
            modal.element.modal();
            modal.close.then(function(result) {
                $scope.message = "You said " + result;
            });
        });
    };

切换功能后,它可以工作,但是... 我如何将数据传递给模态?就像 ui-bs-modal 一样,他们有决心。

【问题讨论】:

  • 您的服务中是否缺少return this;
  • @PrashantGhimire 不需要从服务中返回thisservice 将隐式返回函数的this(context)
  • 很高兴知道! @PankajParkar ;)

标签: angularjs modal-dialog broadcast angular-broadcast


【解决方案1】:

在模态控制器的事件绑定之前,您正在广播事件。因此,在广播事件之前,请确保已注册事件侦听器(意味着已加载模态控制器)。所以在showModal方法之后调用SomeService.testFunction();

$scope.show = function(customer_id) {
    ModalService.showModal({
        templateUrl: 'modal.html',
        inputs: {
            customer_id: customer_id
        },
        scope: $scope,
        controller: function($scope, close) {
           //code as is
           //listeners will get register from here.
        }
    })
   .then(function(modal) {
       SomeService.testFunction(); //broadcasting event
    }).catch(function(error) {
      // error contains a detailed error message.
      console.log(error);
    });
};

【讨论】:

  • 您可能应该从show.modal 承诺中链接,因为它必须异步获取模板URL。
  • @georgeawg 嘿,谢谢你的提醒,伙计。感谢你的收获.. :) 我错过了那个愚蠢的事情 ;)
  • 太好了,它有效。我花了几个小时。 : (
  • 之所以我把它放在模态开放部分的顶部,我不想将参数传递给控制器​​。看来我必须这样做。
  • 你说的是哪些参数
【解决方案2】:

在模态控制器被实例化或创建之前,您正在广播事件,因为在ModalService.showModal 之前调用了服务函数。尝试更改顺序。这应该可以正常工作。

$scope.show里面试试这个顺序

$scope.show = function(){
 ModalService.showModal({
       ....
       // Listen for broadcast event
 });
 SomeService.testFunction();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-28
    • 2016-12-30
    • 1970-01-01
    相关资源
    最近更新 更多