클릭시 확인 대화 상자-AngularJS
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
을 사용하지 않아도 괜찮다면 정상적으로 ng-click
작동합니다. 클릭 핸들러가 두 번 트리거되는 것을 방지하면서 다른 이름으로 이름을 바꾸고 속성을 읽을 수 있습니다.
http://plnkr.co/edit/YWr6o2?p=preview
문제는 terminal
다른 지시문이 실행되지 않도록 지시 하는 것이라고 생각합니다 . 데이터 바인딩 {{ }}
은 ng-bind
지시문 의 별칭 일 뿐이며 terminal
.
깨끗한 지시적 접근.
업데이트 : 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();
}
});
}
}
}
]);
저에게는 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을 참조하십시오.
핵심 자바 스크립트 + 각도 js를 사용하면 매우 간단합니다.
$scope.delete = function(id)
{
if (confirm("Are you sure?"))
{
//do your process of delete using angular js.
}
}
확인을 클릭하면 삭제 작업이 수행되고 그렇지 않으면 수행되지 않습니다. * id는 삭제할 매개 변수, 레코드입니다.
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)
}
});
}
};
}
]);
오늘 날짜에이 솔루션은 저에게 효과적입니다.
/**
* 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
저는 Angular-UI $ modal 서비스에 의존하는 바로이 모듈을 만들었습니다.
https://github.com/Schlogen/angular-confirm
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>
$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;
}
}
코드는 모든 것을 말한다
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();
});
}
};
});
Confirmation dialog can implemented using AngularJS Material:
$mdDialog opens a dialog over the app to inform users about critical information or require them to make decisions. There are two approaches for setup: a simple promise API and regular object syntax.
Implementation example: Angular Material - Dialogs
If you use ui-router, the cancel or accept button replace the url. To prevent this you can return false in each case of the conditional sentence like this:
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;
});
}
}; });
A very simple angular solution
You can use id with a message or without. Without message the default message will show.
Directive
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();
}
});
}
}
}]);
Controller
$scope.sayHello = function(){
alert("hello")
}
HTML
With a message
<span ng-click="sayHello()" ng-confirm-message="Do you want to say Hello ?" >Say Hello!</span>
Without a messsage
<span ng-click="sayHello()" ng-confirm-message>Say Hello!</span>
Here is a clean and simple solution using angular promises $q
, $window
and native .confirm()
modal:
angular.module('myApp',[])
.controller('classicController', ( $q, $window ) => {
this.deleteStuff = ( id ) => {
$q.when($window.confirm('Are you sure ?'))
.then(( confirm ) => {
if ( confirm ) {
// delete stuff
}
});
};
});
Here I'm using controllerAs
syntax and ES6 arrow functions but it's also working in plain ol' ES5.
Delete confirmation popup using bootstrap in angularjs
very simple.. I have one solution for this with using bootstrap conformation popup. Here i am provided
<button ng-click="deletepopup($index)">Delete</button>
in bootstrap model popup:
<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');
};
when i click delete button bootstrap delete conformation popup will open and when i click yes button row will deleted.
I wish AngularJS had a built in confirmation dialog. Often, it is nicer to have a customized dialog than using the built in browser one.
I briefly used the twitter bootstrap until it was discontinued with version 6. I looked around for alternatives, but the ones I found were complicated. I decided to try the JQuery UI one.
Here is my sample that I call when I am about to remove something from 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;
}
}
});
I hope this helps someone. I was pulling my hair out when I needed to upgrade ui-bootstrap-tpls.js but it broke my existing dialog. I came into work this morning, tried a few things and then realized I was over complicating.
참고URL : https://stackoverflow.com/questions/18313576/confirmation-dialog-on-ng-click-angularjs
'Programing' 카테고리의 다른 글
SVN 분기 삭제 (0) | 2020.09.18 |
---|---|
R, xlsx 또는 xls로 Excel 파일 가져 오기 (0) | 2020.09.18 |
AWS CLI 도구에서 AWS 계정 번호를 얻는 빠른 방법은 무엇입니까? (0) | 2020.09.18 |
click () 대신 jQuery on ()을 사용하는 이유 (0) | 2020.09.18 |
pandas.DataFrame을 뒤집는 올바른 방법? (0) | 2020.09.18 |