ng 클릭 시 확인 대화 상자 - 각도JS
.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>
(이 경우는 이름이 평가되지 않습니다).제 지시의 terminal 파라미터 때문인 것 같습니다.해결 방법이 있습니까?
코드를 테스트하려면 http://plnkr.co/edit/EHmRpfwsgSfEFVMgRLgj?p=preview
사용하지 않으셔도 괜찮으시다면ng-click
정상적으로 동작합니다.클릭 핸들러가 두 번 트리거되지 않도록 하면서 다른 이름으로 이름을 바꾸고 속성을 읽을 수 있습니다.
http://plnkr.co/edit/YWr6o2?p=preview
는 ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★terminal
다른 지시사항을 실행하지 않도록 지시합니다.「」와의 데이터 {{ }}
입니다.ng-bind
입니다.terminal
클린 디렉티브 어프로치
갱신: 오래된 답변 (2014)
으로는 ""를 합니다.ng-click
event 、 [ ]에 합니다.ng-confirm-click="message"
사용자에게 확인을 요구합니다.하면 normal confirm( 「 」 )이 됩니다.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/#!/clicks/2013/clicking-ng-click/
갱신: 새로운 답변 (2016년)
1) 'ng'에서 'mw'로 프리픽스를 변경('ng')하여 원어민 각도지향용으로 예약하였다.
2) ng-click 이벤트를 대행 수신하는 대신 기능 및 메시지를 전달하도록 지시문을 변경하였습니다.
3) 커스텀 메시지가 mw-syslog-click-message=syslog에 제공되지 않는 경우 기본 "확실합니까?" 메시지를 추가했습니다.
<!-- 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
}
};
하지만 커스터마이즈 할 수 없을 것 같아요.'이렇게'는 '이러다'는 '이러다'는 '이러다'는 '이러다
편집:
ionic 프레임워크를 사용하는 경우 다음과 같이 ionic Popup 대화상자를 사용해야 합니다.
// 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
}
});
};
자세한 내용은 $ionic Popup을 참조하십시오.
코어 Javascript + angular js를 사용하면 매우 간단합니다.
$scope.delete = function(id)
{
if (confirm("Are you sure?"))
{
//do your process of delete using angular js.
}
}
[확인]을 클릭하면 삭제 작업이 수행되고 그렇지 않으면 수행되지 않습니다.* id는 파라미터입니다.삭제할 레코드를 만듭니다.
은 '아예'를 입니다.terminal: false
그게 버튼 내부의 처리를 방해하고 있기 때문입니다. your에서는 러 instead가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)
}
});
}
};
}
]);
$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;
}
}
코드는 모든 것을 말해준다.
현재 이 솔루션은 다음과 같습니다.
/**
* 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>
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();
});
}
};
});
Angular를 사용하여 확인 대화 상자를 구현할 수 있습니다.JS 재료:
$mdDialog는 사용자에게 중요한 정보를 알리거나 결정을 요구하는 대화상자를 앱 상에서 엽니다.셋업에는 간단한 약속 API와 일반 객체 구문의 두 가지 방법이 있습니다.
구현 예:각도 재료 - 대화상자
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;
});
}
}; });
매우 단순한 각해
id는 메시지와 함께 사용할 수도 있고 사용하지 않을 수도 있습니다.메시지가 없으면 기본 메시지가 표시됩니다.
지시.
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>
각진 .$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
}
});
};
});
에서는 여서 here here기서 here here here here here 。controllerAs
구문 및 ES6 화살표는 기능하지만 일반 ol' ES5에서도 작동합니다.
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');
};
[삭제] 버튼을 클릭하면 부트스트랩 삭제 확인 팝업이 열리고 [예]버튼 행이 삭제됩니다.
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")
}
}
나는 Angular를 바란다.JS에는 확인 대화상자가 내장되어 있습니다.대부분의 경우 내장된 브라우저 대화 상자를 사용하는 것보다 맞춤형 대화 상자를 사용하는 것이 좋습니다.
버전 6에서 단종될 때까지 twitter 부트스트랩을 잠시 사용했습니다.나는 다른 대안을 찾아봤지만, 내가 찾은 것은 복잡했다.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를 업그레이드해야 할 때 머리를 뽑고 있었는데 기존 대화상자가 깨졌습니다.오늘 아침 출근해서 몇 가지 시도를 해보니 내가 너무 복잡하다는 걸 깨달았어.
언급URL : https://stackoverflow.com/questions/18313576/confirmation-dialog-on-ng-click-angularjs
'source' 카테고리의 다른 글
포스트맨 레스트 클라이언트에서 스프링 csrf 토큰을 보내려면 어떻게 해야 합니까? (0) | 2023.08.24 |
---|---|
다른 플러그인 메뉴에 새 사용자 지정 하위 메뉴를 추가하는 방법 (0) | 2023.03.27 |
대규모 비즈니스 애플리케이션을 위한 대응 아키텍처 (0) | 2023.03.27 |
jQuery AJAX 및 JSON 형식 (0) | 2023.03.27 |
Spring websocket stomp 서버에서 클라이언트 세션 연결 해제 (0) | 2023.03.27 |