codememo

outside/esc 클릭 시 Angularjs 부트스트랩모달 종료 콜

tipmemo 2023. 2. 8. 17:58
반응형

outside/esc 클릭 시 Angularjs 부트스트랩모달 종료 콜

프로젝트에서 Angular-ui/bootstrap modal을 사용하고 있습니다.

제 모달은 다음과 같습니다.

$scope.toggleModal = function () {
    $scope.theModal = $modal.open({
        animation: true,
        templateUrl: 'pages/templates/modal.html',
        size: "sm",
        scope: $scope
    });
}

ESC 버튼을 클릭하거나 모달 영역 외부를 클릭하여 모달 닫기를 할 수 있습니다.이 경우 기능을 실행할 수 있는 방법이 있습니까?어떻게 마무리 지어야 할지 잘 모르겠어요.

으로 모달 를 할 수 있습니다.ng-click="closeModal()"음음음같 뭇매하다

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

할 수 있어요.그러면 해제 이벤트가 발생하며 이 경우 약속은 거부됩니다.이 때 할 점은 '아,아,아,아,아,아,아,아,아,아,아,아,아,아,아,아,아,아,아,아.$modal.open()는 메서드가 있는 합니다.result약속하는 자산입니다.

당신이 할 수 있는 약속으로...

//This will run when modal dismisses itself when clicked outside or
//when you explicitly dismiss the modal using .dismiss function.
$scope.theModal.result.catch(function(){
    //Do stuff with respect to dismissal
});

//Runs when modal is closed without being dismissed, i.e when you close it
//via $scope.theModal.close(...);
$scope.theModal.result.then(function(datapassedinwhileclosing){
    //Do stuff with respect to closure
});

단축키로서 다음과 같이 쓸 수 있습니다.

 $scope.theModal.result.then(doClosureFn, doDismissFn);

참조

open 메서드는 다음 속성을 가진 개체인 모달 인스턴스를 반환합니다.

  • close(result) - 모달 닫기 및 결과 전달에 사용할 수 있는 메서드
  • disp(reason) - 이유를 전달하여 모달 해제를 위해 사용할 수 있는 방법
  • result - 모달 종료 시 해결되고 모달 해제 시 거부되는 약속
  • opened - 콘텐츠의 템플릿을 다운로드하고 모든 변수 'modal'을 해결한 후 모달 오픈 시 해결되는 약속 - 모달 렌더링 시 해결되는 약속입니다.

오래된 질문이지만 다양한 종료 액션에 대한 확인 대화상자를 추가하려면 다음 사항을 모달인스턴스 컨트롤러에 추가합니다.

$scope.$on('modal.closing', function(event, reason, closed) {
    console.log('modal.closing: ' + (closed ? 'close' : 'dismiss') + '(' + reason + ')');
    var message = "You are about to leave the edit view. Uncaught reason. Are you sure?";
    switch (reason){
        // clicked outside
        case "backdrop click":
            message = "Any changes will be lost, are you sure?";
            break;

        // cancel button
        case "cancel":
            message = "Any changes will be lost, are you sure?";
            break;

        // escape key
        case "escape key press":
            message = "Any changes will be lost, are you sure?";
            break;
    }
    if (!confirm(message)) {
        event.preventDefault();
    }
});

오른쪽 상단에 닫기 버튼이 있는데, 이 버튼은 "취소" 동작을 유발합니다.배경(활성화된 경우)을 클릭하면 취소 액션이 트리거됩니다.이를 사용하여 다양한 종료 이벤트에 대해 서로 다른 메시지를 사용할 수 있습니다.다른 사람들에게 도움이 될 수 있도록 공유하려고요.

$modal.open() 메서드에서 반환된 "result" 약속을 사용할 수 있습니다.아래와 같이:

 $scope.toggleModal = function () {
      $scope.theModal = $modal.open({
          animation: true,
          templateUrl: 'pages/templates/modal.html',
          size: "sm",
          scope: $scope
      });

      $scope.theModal.result.then(function(){
          console.log("Modal Closed!!!");
      }, function(){
          console.log("Modal Dismissed!!!");
      });
 }

또한 다음과 같이 "결과" 약속의 "최종" 콜백을 사용할 수 있습니다.

     $scope.theModal.result.finally(function(){
          console.log("Modal Closed!!!");
      });

제 경우 모달의 클릭을 해제하면 모달 형식의 저장되지 않은 데이터가 모두 폐기된다는 경고를 사용자에게 표시하려고 했습니다.이를 수행하려면 모달에서 다음 옵션을 설정하십시오.

var myModal = $uibModal.open({
          controller: 'MyModalController',
          controllerAs: 'modal',
          templateUrl: 'views/myModal.html',
          backdrop: 'static',
          keyboard: false,
          scope: modalScope,
          bindToController: true,
        });

이렇게 하면 모달은 꺼질 때 닫히지 않습니다.

backdrop: 'static'

이렇게 하면 'esc'를 누를 때 모달 닫힘이 방지됩니다.

keyboard: false

다음으로 모달 컨트롤러에서 커스텀 "취소" 기능을 추가합니다.이 경우 사용자가 모달 닫기를 원하는지 묻는 Sweet Alert가 나타납니다.

  modal.cancel = function () {
    $timeout(function () {
      swal({
        title: 'Attention',
        text: 'Do you wish to discard this data?',
        type: 'warning',
        confirmButtonText: 'Yes',
        cancelButtonText: 'No',
        showCancelButton: true,
      }).then(function (confirm) {
        if (confirm) {
          $uibModalInstance.dismiss('cancel');
        }
      });
    })
  };

마지막으로 모달 컨트롤러 내에 다음 이벤트청취자를 추가합니다.

  var myModal = document.getElementsByClassName('modal');
  var myModalDialog = document.getElementsByClassName('modal-dialog');

  $timeout(function () {
    myModal[0].addEventListener("click", function () {
      console.log('clicked')
      modal.cancel();
    })

    myModalDialog[0].addEventListener("click", function (e) {
      console.log('dialog clicked')
      e.stopPropagation();
    })
  }, 100);

myModal은 modal.cancel() 콜백 함수를 호출하는 요소입니다."myModalDialog"는 모달 콘텐츠 창입니다. "myModal"로 버블이 발생하지 않도록 이 요소에 대한 이벤트 전파를 중지합니다.

이것은 모달의 클릭(즉, 배경 클릭)에만 유효합니다.'esc'를 눌러도 이 콜백은 트리거되지 않습니다.

대신ng-click="closeModal()"해 볼 수 있습니다ng-click="$dismiss()"

<button ng-click="$dismiss()">Close</button>

이렇게 컨트롤러에서도 jquery 이벤트를 On이라고 할 수 있습니다.여기서 "viewImageModal"은 모달 팝업 ID입니다.

constructor($scope: AuditAppExtension.IActionPlanScope, dataSvc: ActionPlanService, Upload, $timeout, $mdToast: any) {

            $('#viewImageModal').on('shown.bs.modal', function (e) {
                console.log("shown", e);

                $scope.paused = false;
                $modal.find('.carousel').carousel('cycle');
            });

            $('#viewImageModal').on('hide.bs.modal', function (e) {
                console.log("hide", e);

                return true;
            });
}

언급URL : https://stackoverflow.com/questions/30356844/angularjs-bootstrap-modal-closing-call-when-clicking-outside-esc

반응형