在angularjs中如何从外部指令触发主html页面中的弹出窗口

How to trigger popup window in the main html page from outside directive in angularjs?

本文关键字:html 窗口 angularjs 从外部 指令      更新时间:2023-09-26

在主html中,有两个弹出窗口。一个窗口的一段代码是这样的:

<div id="new-asset-modal" > 
     <div class="modal-dialog"> 
      <div class="modal-content"> 
       <div class="modal-header> 
        <h4 class="modal-title>Type A Record Name</h4> 
       </div> 
       <div class="modal-body"> 
        <input ng-model="a" type="text" aria-describedby="basic-addon1" /> 
       </div> 
       <div class="modal-footer"> 
        <button type="button" data-dismiss="modal">Cancel</button> 
        <button type="button" data-dismiss="modal" id="modal-save" ng-click="add()">Save</button> 
       </div> 
      </div> 
     </div> 
    </div> 

当然,还有另一种模式叫做"B类记录名称"

在主html中,我使用了这样的指令

<directivetest></directivetest>
在控件中,代码是这样的:
  .directive("directivetest",function(){
                    return{
                    restrict:'EA',
                    replace: true,
                    templateUrl: "testpage.html",
                    controller:[ $scope,function($scope){
                    $scope.popaction=function(c){.....};
                     }]
    }
    );}
在testpage.html中,有一个按钮
<button ng-click="popaction(c);">Button1</button>   

我想要一个这样的函数:当Button1被按下时,如果参数等于"a",那么"Type a modal"被触发/显示在主页面;如果参数等于"b",则触发/显示"Type b modal"。

谢谢! !

一个想法是$broadcast一条来自您的指令的消息,该消息包含被单击的类型,然后在主控制器中使用$on来侦听消息并在收到时采取相应的行动。

在指令控制器中:

$scope.popaction=function(type){
    $scope.$broadcast("BUTTON_CLICKED", {"type":type});
};

在主控制器中:

$scope.$on("BUTTON_CLICKED", function(event, args) {
    if(args.type === 'a') {
        doModalA();
    }
});

至于如何触发模态,我使用了ng-dialog并且非常喜欢它。文档是非常好的,但基本上你包括js文件和注入ngDialog,然后做一些像:

function doModalA() {
    ngDialog.open({ template: 'popupTmpl.html' });
}

您还可以使用ngDialog.openConfirm并等待承诺返回,以便您可以根据用户与您的模式的交互执行操作。你也可以传递给它数据,你的范围,给模态它自己的控制器,等等。它可以非常简单地使用,但它非常灵活,可以做更复杂的事情。

最后,您可能需要从您的模态中创建模板,这很容易。只需要在main。html中包含这样的内容,把你的模态内容放进去,然后随意命名

<script type="text/ng-template" id="/popupTmpl.html">
    Content of the template.
</script>