首页 > 解决方案 > 以uib模式在控制器之间传递数据

问题描述

我在我的 angularjs 应用程序中编写了一个常见的uib 模态。它的正文和页脚的内容需要根据某些情况进行更改,所以我现在就这样给出了它。该代码实际上工作正常,但需要确保我是否以正确的方式做事......

在这里单击模态按钮时,我实际上是在比较单击的按钮的文本。我不希望模态作为指令。

HTML 代码

<div class="modal-header" >
   <button type="button" class="close" ng-click="close()" data-dismiss="modal">&times;</button>
   <h4><b>{{customModal.title}}</b></h4>
</div>
<div class="modal-body">
 {{customModal.body}}
</div>
<div class="modal-footer" >  
   <span ng-repeat="item in customModal.buttons">
   <button type="button" class="{{item.btnClass}}" ng-click="modalBtnClick(customModal,item);close()" data-dismiss="modal" ng-if="item.show">{{item.text}}</button>
   <span>
</div>

单击时调用模态......

$scope.areYouSureModalInstance = $uibModal.open({
  animation: true,
  templateUrl: 'views/Modal.html',
  controller: 'ModalCtrl',
  windowClass: 'nested-modal',
  scope: $scope,
  resolve: {
    items: function() {
      let btns=[
          {id:1,text:"Yes",show:true, btnClass:"btn btn-success"},
          {id:2,text:"No",show:true, btnClass:"btn btn-danger"},
          {id:3,text:"Cancel",show:true, btnClass:"btn btn-default"}
        ];
      $scope.customModal = {
        id:'confirm',
        title:'Confirm',
        body:'Do you want to save the changes you have made?',
        buttons:btns
      };
      //passes the modal properties
      return $scope.customModal;
    }
  }
});

 //Inside the uib modal controller

   function ModalCtrl($scope) {

    $scope.close = function() {
      $scope.areYouSureModalInstance.close();
    };

     $scope.modalBtnClick=function(data,btn){
      if(data.id==="confirm"){
       $scope.$emit('close.confirm',btn);
      }
   };
 }


//If the user clicks on any button



$scope.$on('close.confirm', function(event, data) {

if (data.text.toLowerCase()==="no") {
  //do some stuff here
 }
if (data.text.toLowerCase()==="yes") {
  //do some stuff here
}
$scope.modalInstance.close();
});

有没有更好的方法可以用两个控制器而不是使用模态指令来做到这一点......

标签: angularjsangular-ui-bootstrap

解决方案


$uibModal.open().result返回一个承诺。

因此,通过执行订阅承诺结果

$scope.areYouSureModalInstance.then(function(args) {
  //arguments that the modal returned
  console.log(args);
},function () {
  //errors
});

用于关闭和确认方法

 function ModalCtrl($scope, $uibModalInstance) {

 $scope.close = function() {
   $uibModalInstance.dismiss();
 };

 $scope.modalBtnClick=function(data,btn){
  if(data.id==="confirm"){
   // btn -> arguments that you pass
   $uibModalInstance.close(btn);
  }
 };
}

推荐阅读