角度 从模态实例公开函数



我使用了另一个堆栈溢出问题中的这段代码

$modalInstance.opened.then(function(){
  alert('hi');
});

在警报部分,我想调用驻留在模态控制器上的函数。我该怎么做?

我的模式呼叫如下

this.OpenMyModal = function(){
  var modalInstance = $modal.open({
        backdrop: 'static',
        templateUrl: 'MyAddress/MyController/MyMethod',
        controller: 'modalController',         
        resolve: {              
           myTemplateUrl: function(){                   
               return myTemplateUrl;
                }           
        }
    });
modalInstance.rendered.then(function () {
      /*modalcontroller function to call goes here;*/
    modalController.SearchClick();
    });
  return modalInstance.result.then(function (returnedInput) {
        return returnedInput;
    }, function () {
        // dismissed with cancel button
        return "";
    })
}

目前模态控制器用于搜索。在我要调用的模态控制器中有一个 onclick 函数。控制器上的函数称为

$scope.SearchClick = function()
{
$scope.Search();
}

如果我在初始化控制器时调用 click 函数,它将破坏使用此相同控制器的其他项目的功能。

当我调用这个控制器时,我只需要能够调用这个简单的函数。

这是一个 plunker

在这个 plunker 中,我以两种方式调用模态内的函数。

在第一种方式中,我在模态出现后立即调用模态函数。在第二种方式中,我使用事件调用模态函数。我从控制器触发此事件,在模态控制器中,我有一个侦听器在等待此事件。

方法一:在模态控制器中创建一个"初始化"方法(只是一个示例)。

function initialize() {
    // Here you can call your function
    console.log('Method 1, Call your function now!');
    $scope.myFunctionInsideModal();
}

并在模态控制器中调用此方法

initialize(); // Initialize stuff

方法2:从控制器触发事件

 $rootScope.$broadcast('myCustomEvent', 'any data');

并在模态控制器中放置一个侦听器:

$scope.$on('myCustomEvent', function(event, data) {
    // Here you can call your function
    console.log('Method 2, Call your function now! ');
    $scope.myFunctionInsideModal();
})

希望对您有所帮助。
有关更多详细信息和工作示例,请参阅plunker。

最新更新