클릭시 확인 대화 상자-AngularJS


85

ng-click사용자 지정 angularjs 지시문을 사용하여 확인 대화 상자를 설정하려고합니다 .

app.directive('ngConfirmClick', [
    function(){
        return {
            priority: 1,
            terminal: true,
            link: function (scope, element, attr) {
                var msg = attr.ngConfirmClick || "Are you sure?";
                var clickAction = attr.ngClick;
                element.bind('click',function (event) {
                    if ( window.confirm(msg) ) {
                        scope.$eval(clickAction)
                    }
                });
            }
        };
}])

이것은 훌륭하게 작동하지만 불행히도 내 지시문을 사용하는 태그 내의 표현식은 평가되지 않습니다.

<button ng-click="sayHi()" ng-confirm-click="Would you like to say hi?">Say hi to {{ name }}</button>

(이 경우 이름은 평가되지 않습니다). 내 지시문의 터미널 매개 변수 때문인 것 같습니다. 해결 방법에 대한 아이디어가 있습니까?

내 코드를 테스트하려면 : http://plnkr.co/edit/EHmRpfwsgSfEFVMgRLgj?p=preview


이 경우 왜 터미널을 사용합니까? 없이 완벽하게 작동하는 것 같습니다 (그리고 당신은 그것을 알고 있습니다). 당신의 지시에 왜 필요하다고 생각하는지 궁금합니다.
— Simon Belanger

@SimonBelanger 터미널 = false 인 경우 확인 대화 상자에서 "취소"를 클릭해도 sayHi ()가 트리거됩니다. 내 목표는 사용자가 취소를 클릭하면 sayHi ()를 호출하지 않는 것입니다.
— poiuytrez

답변:


92

를 사용하지 않아도 괜찮다면 정상적으로 ng-click작동합니다. 클릭 핸들러가 두 번 트리거되는 것을 방지하면서 다른 이름으로 이름을 바꾸고 속성을 읽을 수 있습니다.

http://plnkr.co/edit/YWr6o2?p=preview

문제는 terminal다른 지시문이 실행되지 않도록 지시 하는 것이라고 생각합니다 . 데이터 바인딩 {{ }}은 ng-bind지시문 의 별칭 일 뿐이며 terminal.


13
이 코드 조각은 현재 버전의 angular에서 더 이상 작동하지 않습니다. scope. $ eval (..)은 scope. $ apply (..)로 대체되어야합니다.
— CoolTapes 2014 년

E2E-테스트와 JS 확인 대화 상자이 질문을 확인하십시오 stackoverflow.com/questions/16424961/...
— ndequeker

작동하지만 크롬의 "추가 대화 상자를 만들려면이 페이지 사용 안 함"확인란을 선택하면 어떻게됩니까? : s
— bigpony

58

깨끗한 지시적 접근.

업데이트 : Old Answer (2014)

기본적으로 ng-click이벤트를 가로 채고 ng-confirm-click="message"지시문에 포함 된 메시지를 표시 하고 사용자에게 확인을 요청합니다. 확인을 클릭하면 정상이 ng-click실행되고 그렇지 않으면 스크립트가 종료되고 ng-click실행되지 않습니다.

<!-- index.html -->
<button ng-click="publish()" ng-confirm-click="You are about to overwrite your PUBLISHED content!! Are you SURE you want to publish?">
  Publish
</button>
// /app/directives/ng-confirm-click.js
Directives.directive('ngConfirmClick', [
  function(){
    return {
      priority: -1,
      restrict: 'A',
      link: function(scope, element, attrs){
        element.bind('click', function(e){
          var message = attrs.ngConfirmClick;
          // confirm() requires jQuery
          if(message && !confirm(message)){
            e.stopImmediatePropagation();
            e.preventDefault();
          }
        });
      }
    }
  }
]);

Zach Snow의 코드 크레딧 : http://zachsnow.com/#!/blog/2013/confirming-ng-click/

업데이트 : 새로운 답변 (2016)

1) 접두어가 'ng'에서 'mw'로 변경되었습니다. 전자 ( 'ng')는 기본 각도 지시문 용으로 예약되어 있습니다.

2) ng-click 이벤트를 가로채는 대신 함수와 메시지를 전달하도록 지시문을 수정했습니다.

3) 기본 "확실합니까?"추가 mw-confirm-click-message = ""에 사용자 정의 메시지가 제공되지 않은 경우 메시지.

<!-- index.html -->
<button mw-confirm-click="publish()" mw-confirm-click-message="You are about to overwrite your PUBLISHED content!! Are you SURE you want to publish?">
  Publish
</button>
// /app/directives/mw-confirm-click.js
"use strict";

var module = angular.module( "myApp" );
module.directive( "mwConfirmClick", [
  function( ) {
    return {
      priority: -1,
      restrict: 'A',
      scope: { confirmFunction: "&mwConfirmClick" },
      link: function( scope, element, attrs ){
        element.bind( 'click', function( e ){
          // message defaults to "Are you sure?"
          var message = attrs.mwConfirmClickMessage ? attrs.mwConfirmClickMessage : "Are you sure?";
          // confirm() requires jQuery
          if( confirm( message ) ) {
            scope.confirmFunction();
          }
        });
      }
    }
  }
]);

8
NB는, jQuery를 요구하는
— eggonlegs

1
이것은 나를 위해 작동하지 않습니다. 확인이 표시되지 않고 클릭이 계속됩니다. 다른 누군가?
— OneHoopyFrood

내가 먼저하지 때어 NG 클릭 클릭 핸들러에 나쁜 아이디어라고 생각하고 정지 즉시에 의존하고 기본을 방지
— 제임스 Kleeh에게

OneHoopyFrood, ng-click = ""에 유효한 함수가 있어야합니다. 그렇지 않으면 실패합니다. 감사.
— mikeborgh

2 단계) ng-click 이벤트를 가로채는 대신 함수와 메시지를 전달하도록 지시문을 수정 한 이유는 무엇입니까?
— Silver

46

저에게는 https://www.w3schools.com/js/js_popup.asp , 브라우저의 기본 확인 대화 상자가 많이 작동했습니다. 방금 시도했습니다.

$scope.delete = function() {
    if (confirm("sure to delete")) {
        // todo code for deletion
    }
};

Simple .. :)
하지만 커스터마이징이 불가능하다고 생각합니다. "취소"또는 "확인"버튼과 함께 나타납니다.

편집하다:

ionic 프레임 워크를 사용하는 경우 다음과 같이 ionicPopup 대화 상자를 사용해야합니다.

// A confirm dialog


$scope.showConfirm = function() {
   var confirmPopup = $ionicPopup.confirm({
     title: 'Delete',
     template: 'Are you sure you want to delete this item?'
   });

   confirmPopup.then(function(res) {
     if(res) {
       // Code to be executed on pressing ok or positive response
       // Something like remove item from list
     } else {
       // Code to be executed on pressing cancel or negative response
     }
   });
 };

자세한 내용은 $ ionicPopup을 참조하십시오.


실제로 깨끗해 보이지만 Angular의 선언적 접근 방식에 위배되는 것 같습니다. 이 접근 방식을 사용하면 컨트롤러 내부에 뷰 로직을 쉽게 넣을 수 있습니다. 가능하다면 컨트롤러를 UI 요소로부터 깨끗하게 유지하는 것이 도움이 될 수 있습니다.
— Jim Aho

1
이미 부울을 반환 == true하기 때문에이 경우 완전히 불필요한를 제거 할 수 있습니다 confirm(). JS로 하여금 그것을 강제로 입력하고 사실과 비교할 필요가 없습니다.
— Léo Lam

10

핵심 자바 스크립트 + 각도 js를 사용하면 매우 간단합니다.

$scope.delete = function(id) 
    { 
       if (confirm("Are you sure?"))
           {
                //do your process of delete using angular js.
           }
   }

확인을 클릭하면 삭제 작업이 수행되고 그렇지 않으면 수행되지 않습니다. * id는 삭제할 매개 변수, 레코드입니다.


5

terminal: false버튼 내부의 처리를 차단하는 것이기 때문에 사용하고 싶지 않습니다 . 대신에 기본 동작을 방지하기 위해 link클리어합니다 attr.ngClick.

http://plnkr.co/edit/EySy8wpeQ02UHGPBAIvg?p=preview

app.directive('ngConfirmClick', [
  function() {
    return {
      priority: 1,
      link: function(scope, element, attr) {
        var msg = attr.ngConfirmClick || "Are you sure?";
        var clickAction = attr.ngClick;
        attr.ngClick = "";
        element.bind('click', function(event) {
          if (window.confirm(msg)) {
            scope.$eval(clickAction)
          }
        });
      }
    };
  }
]);

plunker에서 참조하는 Angular 버전에서 작동하지만 ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js를 참조하면 예상대로 작동하지 않습니다.
— ChrisW 2014 년

궁극적으로 내가 제안한 접근 방식은 ngClick이 '클릭'에 대한 단순한 바인딩 이상을 수행하기 때문에 일부 경우에만 작동합니다. 더 정확한 접근 방식은 별도의 속성을 통하지 않고 ng-click 핸들러에서 확인을 처리하는 것입니다.
— Stepan Riha 2014 년

4

오늘 날짜에이 솔루션은 저에게 효과적입니다.

/**
 * A generic confirmation for risky actions.
 * Usage: Add attributes: ng-really-message="Are you sure"? ng-really-click="takeAction()" function
 */
angular.module('app').directive('ngReallyClick', [function() {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            element.bind('click', function() {
                var message = attrs.ngReallyMessage;
                if (message && confirm(message)) {
                    scope.$apply(attrs.ngReallyClick);
                }
            });
        }
    }
}]);

크레딧 : https://gist.github.com/asafge/7430497#file-ng-really-js



4

ng-click컴파일을 사용하여 ng-click표현식 을 래핑하면 함께 작동하는 각도 전용 솔루션 이 가능 합니다.

지령:

.directive('confirmClick', function ($window) {
  var i = 0;
  return {
    restrict: 'A',
    priority:  1,
    compile: function (tElem, tAttrs) {
      var fn = '$$confirmClick' + i++,
          _ngClick = tAttrs.ngClick;
      tAttrs.ngClick = fn + '($event)';

      return function (scope, elem, attrs) {
        var confirmMsg = attrs.confirmClick || 'Are you sure?';

        scope[fn] = function (event) {
          if($window.confirm(confirmMsg)) {
            scope.$eval(_ngClick, {$event: event});
          }
        };
      };
    }
  };
});

HTML :

<a ng-click="doSomething()" confirm-click="Are you sure you wish to proceed?"></a>

3
    $scope.MyUpdateFunction = function () {
        var retVal = confirm("Do you want to save changes?");
        if (retVal == true) {
            $http.put('url', myData).
            success(function (data, status, headers, config) {
                alert('Saved');
            }).error(function (data, status, headers, config) {
                alert('Error while updating');
            });
            return true;
        } else {
            return false;
        }
    }

코드는 모든 것을 말한다


1

HTML 5 코드 샘플

<button href="#" ng-click="shoutOut()" confirmation-needed="Do you really want to
shout?">Click!</button>

AngularJs 사용자 지정 지시문 코드 샘플

var app = angular.module('mobileApp', ['ngGrid']);
app.directive('confirmationNeeded', function () {
    return {
    link: function (scope, element, attr) {
      var msg = attr.confirmationNeeded || "Are you sure?";
      var clickAction = attr.ngClick;
      element.bind('click',function (e) {
        scope.$eval(clickAction) if window.confirm(msg)
        e.stopImmediatePropagation();
        e.preventDefault();
       });
     }
    };
});

1

확인 대화 상자는 AngularJS 재질을 사용하여 구현할 수 있습니다 .

$ mdDialog는 앱에서 대화 상자를 열어 사용자에게 중요한 정보를 알리거나 결정을 요구합니다. 설정에는 두 가지 접근 방식이 있습니다. 간단한 promise API와 일반 객체 구문입니다.

구현 예 : Angular Material-대화 상자


0

ui-router를 사용하는 경우 취소 또는 수락 버튼이 URL을 대체합니다. 이를 방지하기 위해 다음과 같은 조건 문의 각 경우에 false를 반환 할 수 있습니다.

app.directive('confirmationNeeded', function () {
  return {
    link: function (scope, element, attr) {
      var msg = attr.confirmationNeeded || "Are you sure?";
      var clickAction = attr.confirmedClick;
      element.bind('click',function (event) {
      if ( window.confirm(msg) )
        scope.$eval(clickAction);
      return false;
    });
  }
}; });

0

매우 간단한 각도 솔루션

메시지 유무에 관계없이 아이디를 사용할 수 있습니다. 메시지가 없으면 기본 메시지가 표시됩니다.

지령

app.directive('ngConfirmMessage', [function () {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            element.on('click', function (e) {
                var message = attrs.ngConfirmMessage || "Are you sure ?";
                if (!confirm(message)) {
                    e.stopImmediatePropagation();
                }
            });
        }
    }
}]);

제어 장치

$scope.sayHello = function(){
    alert("hello")
}

HTML

메시지와 함께

<span ng-click="sayHello()" ng-confirm-message="Do you want to say Hello ?" >Say Hello!</span>

메시지없이

<span ng-click="sayHello()" ng-confirm-message>Say Hello!</span>

0

여기에 각 약속을 사용하여 깨끗하고 간단한 솔루션 $q, $window네이티브 .confirm()모달은 :

angular.module('myApp',[])
  .controller('classicController', ( $q, $window ) => {
    this.deleteStuff = ( id ) => {
      $q.when($window.confirm('Are you sure ?'))
        .then(( confirm ) => {
          if ( confirm ) {
            // delete stuff
          }
        });
    };
  });

여기에서는 controllerAs구문과 ES6 화살표 함수를 사용 하고 있지만 일반 ES5에서도 작동합니다.


0

angularjs에서 부트 스트랩을 사용하여 확인 팝업 삭제

매우 간단합니다 .. 부트 스트랩 컨 포메이션 팝업을 사용하는 한 가지 해결책이 있습니다. 여기에 제공됩니다

<button ng-click="deletepopup($index)">Delete</button>

부트 스트랩 모델 팝업에서 :

<div class="modal-footer">
  <a href="" data-dismiss="modal" ng-click="deleteData()">Yes</a>
  <a href="" data-dismiss="modal">No</a>
</div>

js

var index=0;
$scope.deleteData=function(){
    $scope.model.contacts.splice(index,1);
}
// delete a row 
$scope.deletepopup = function ($index) {
    index=$index;
    $('#myModal').modal('show');
};

삭제 버튼을 클릭하면 부트 스트랩 삭제 확인 팝업이 열리고 예 버튼을 클릭하면 행이 삭제됩니다.


0

ng-click return 확인 100 % 작동

HTML 파일에서 delete_plot () 함수 호출

<i class="fa fa-trash delete-plot" ng-click="delete_plot()"></i> 
 
  

이것을 컨트롤러에 추가하십시오

    $scope.delete_plot = function(){
        check = confirm("Are you sure to delete this plot?")
        if(check){
            console.log("yes, OK pressed")
        }else{
            console.log("No, cancel pressed")

        }
    }

-1

AngularJS에 확인 대화 상자가 내장되어 있기를 바랍니다. 종종 내장 된 브라우저를 사용하는 것보다 사용자 정의 된 대화 상자를 갖는 것이 더 좋습니다.

버전 6에서 중단 될 때까지 트위터 부트 스트랩을 잠깐 사용했습니다. 대안을 찾아 보았지만 찾은 것은 복잡했습니다. JQuery UI를 사용해보기로했습니다.

다음은 ng-grid에서 무언가를 제거하려고 할 때 호출하는 샘플입니다.

    // Define the Dialog and its properties.
    $("<div>Are you sure?</div>").dialog({
        resizable: false,
        modal: true,
        title: "Modal",
        height: 150,
        width: 400,
        buttons: {
            "Yes": function () {
                $(this).dialog('close');
                //proceed with delete...
                /*commented out but left in to show how I am using it in angular
                var index = $scope.myData.indexOf(row.entity);

                $http['delete']('/EPContacts.svc/json/' + $scope.myData[row.rowIndex].RecordID).success(function () { console.log("groovy baby"); });

                $scope.gridOptions.selectItem(index, false);
                $scope.myData.splice(index, 1);
                */
            },
            "No": function () {
                $(this).dialog('close');
                return;
            }
        }
    });

누군가에게 도움이되기를 바랍니다. ui-bootstrap-tpls.js를 업그레이드해야 할 때 머리카락을 꺼내고 있었지만 기존 대화 상자가 깨졌습니다. 나는 오늘 아침에 출근하여 몇 가지 시도를 한 후 내가 너무 복잡하다는 것을 깨달았습니다.

당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.