programing

Angular에서 간단한 부트스트랩 예/아니오 확인 또는 알림 경고 생성JS

mytipbox 2023. 3. 14. 21:19
반응형

Angular에서 간단한 부트스트랩 예/아니오 확인 또는 알림 경고 생성JS

각도 이외의 환경에서는 매우 간단합니다.html과 js 코드 두 줄만 있으면 화면에 모달 확인 대화상자가 나타납니다.

이제 Angular를 개발하고 있습니다.JS프로젝트에서는 ui-bootstrap modal 확인 다이얼로그를 사용하고 있습니다만, 「이 레코드를 삭제해도 될까요?」라고 하는 간단한 것에도 새로운 컨트롤러를 작성하는 것에 싫증이 납니다.

당신은 이러한 간단한 상황을 어떻게 대처합니까?나는 몇몇 사람들이 요구를 단순화하기 위해 몇 가지 지침을 썼다고 확신한다.

당신의 경험이나 그 주제에 대해 알고 있는 프로젝트를 공유해 주었으면 합니다.

재사용 가능한 서비스를 만듭니다.여기서 읽다

코드:

angular.module('yourModuleName').service('modalService', ['$modal',
// NB: For Angular-bootstrap 0.14.0 or later, use $uibModal above instead of $modal
function ($modal) {

    var modalDefaults = {
        backdrop: true,
        keyboard: true,
        modalFade: true,
        templateUrl: '/app/partials/modal.html'
    };

    var modalOptions = {
        closeButtonText: 'Close',
        actionButtonText: 'OK',
        headerText: 'Proceed?',
        bodyText: 'Perform this action?'
    };

    this.showModal = function (customModalDefaults, customModalOptions) {
        if (!customModalDefaults) customModalDefaults = {};
        customModalDefaults.backdrop = 'static';
        return this.show(customModalDefaults, customModalOptions);
    };

    this.show = function (customModalDefaults, customModalOptions) {
        //Create temp objects to work with since we're in a singleton service
        var tempModalDefaults = {};
        var tempModalOptions = {};

        //Map angular-ui modal custom defaults to modal defaults defined in service
        angular.extend(tempModalDefaults, modalDefaults, customModalDefaults);

        //Map modal.html $scope custom properties to defaults defined in service
        angular.extend(tempModalOptions, modalOptions, customModalOptions);

        if (!tempModalDefaults.controller) {
            tempModalDefaults.controller = function ($scope, $modalInstance) {
                $scope.modalOptions = tempModalOptions;
                $scope.modalOptions.ok = function (result) {
                    $modalInstance.close(result);
                };
                $scope.modalOptions.close = function (result) {
                    $modalInstance.dismiss('cancel');
                };
            };
        }

        return $modal.open(tempModalDefaults).result;
    };

}]);

표시용 html

<div class="modal-header">
  <h3>{{modalOptions.headerText}}</h3>
</div>
<div class="modal-body">
  <p>{{modalOptions.bodyText}}</p>
</div>
<div class="modal-footer">
  <button type="button" class="btn" 
          data-ng-click="modalOptions.close()">{{modalOptions.closeButtonText}}</button>
  <button class="btn btn-primary" 
          data-ng-click="modalOptions.ok();">{{modalOptions.actionButtonText}}</button>
</div>

이 일이 끝나면...아래 예시와 같이 대화 상자를 만들고 싶은 곳에 위의 서비스를 삽입하기만 하면 됩니다.

 $scope.deleteCustomer = function () {

    var custName = $scope.customer.firstName + ' ' + $scope.customer.lastName;


    var modalOptions = {
        closeButtonText: 'Cancel',
        actionButtonText: 'Delete Customer',
        headerText: 'Delete ' + custName + '?',
        bodyText: 'Are you sure you want to delete this customer?'
    };

    modalService.showModal({}, modalOptions)
        .then(function (result) {
             //your-custom-logic
        });
}

제 예를 보실 수 있습니다.내가 뭘 했든 간에

  <div ng-app="myApp" ng-controller="firstCtrl">
    <button ng-click="delete(1);">Delete </button>
  </div>

대본

 var app = angular.module("myApp", []);
 app.controller('firstCtrl', ['$scope','$window', function($scope,$window) {
  $scope.delete = function(id) {
    deleteUser = $window.confirm('Are you sure you want to delete the Ad?');
    if(deleteUser){
     //Your action will goes here
     alert('Yes i want to delete');
    }
  };
 }])

Angular Confirm 라이브러리를 사용할 수 있습니다.

포함되면 지침으로 사용할 수 있습니다.

<button type="button" ng-click="delete()" confirm="Are you sure?">Delete</button>

서비스와 함께:

angular.module('MyApp')
  .controller('MyController', function($scope, $confirm) {
    $scope.delete = function() {
      $confirm({text: 'Are you sure you want to delete?', title: 'Delete it', ok: 'Yes', cancel: 'No'})
        .then(function() {
          // send delete request...
        });
    };
  });

ng-click으로 트리거되는 코드가 있는 경우 confirm 속성을 추가합니다.

<a confirm="Are you sure?" ng-click="..."></a>

(내 것이 아니라 웹에서 찾을 수 있다)에서 온 확인입니다.

app.controller('ConfirmModalController', function($scope, $modalInstance, data) {
        $scope.data = angular.copy(data);

        $scope.ok = function() {
            $modalInstance.close();
        };

        $scope.cancel = function() {
            $modalInstance.dismiss('cancel');
        };
    }).value('$confirmModalDefaults', {
        template: '<div class="modal-header"><h3 class="modal-title">Confirm</h3></div><div class="modal-body">{{data.text}}</div><div class="modal-footer"><button class="btn btn-primary" ng-click="ok()">OK</button><button class="btn btn-warning" ng-click="cancel()">Cancel</button></div>',
        controller: 'ConfirmModalController'
    }).factory('$confirm', function($modal, $confirmModalDefaults) {
        return function(data, settings) {
            settings = angular.extend($confirmModalDefaults, (settings || {}));
            data = data || {};

            if ('templateUrl' in settings && 'template' in settings) {
                delete settings.template;
            }

            settings.resolve = { data: function() { return data; } };

            return $modal.open(settings).result;
        };
    })
    .directive('confirm', function($confirm) {
        return {
            priority: 1,
            restrict: 'A',
            scope: {
                confirmIf: "=",
                ngClick: '&',
                confirm: '@'
            },
            link: function(scope, element, attrs) {
                function reBind(func) {
                    element.unbind("click").bind("click", function() {
                        func();
                    });
                }

                function bindConfirm() {
                    $confirm({ text: scope.confirm }).then(scope.ngClick);
                }

                if ('confirmIf' in attrs) {
                    scope.$watch('confirmIf', function(newVal) {
                        if (newVal) {
                            reBind(bindConfirm);
                        } else {
                            reBind(function() {
                                scope.$apply(scope.ngClick);
                            });
                        }
                    });
                } else {
                    reBind(bindConfirm);
                }
            }
        }
    })

Google FOO에서 오류가 발생하여 원본 사이트를 찾을 수 없습니다.찾으면 업데이트 하겠습니다.

이렇게 간단한 공장을 만들 수 있습니다.

angular.module('app')
.factory('modalService', [
    '$modal', function ($modal) {
        var self = this;
        var modalInstance = null;
        self.open = function (scope, path) {
            modalInstance = $modal.open({
                templateUrl: path,
                scope: scope
            });
        };

        self.close = function () {
            modalInstance.dismiss('close');
        };
        return self;
        }
]);

컨트롤러 내

angular.module('app').controller('yourController',  
  ['$scope','modalService',function($scope,modalService){

$scope.openModal=function(){
 modalService.open($scope,'modal template path goes here');
 };

$scope.closeModal=function(){
 modalService.close();
//do something on modal close
 };
 }]);

합격했습니다$scopecloseModal 함수에 액세스 할 수 있도록 컨트롤러에서 데이터에 액세스 할 수 있도록 합니다.html에서

<button ng-click="openModal()">Open Modal</button>

언급URL : https://stackoverflow.com/questions/29602222/create-a-simple-bootstrap-yes-no-confirmation-or-just-notification-alert-in-angu

반응형