Create a simple Bootstrap Yes/No confirmation or just notification alert in AngularJS

后端 未结 5 1667
灰色年华
灰色年华 2020-12-02 18:49

It\'s so simple in a non-Angular environment. Just html and a two line of js code to show a modal confirmation dialog on the screen.

Now I am developting an AngularJ

相关标签:
5条回答
  • 2020-12-02 18:58

    You can see my example. whatever i'v done.

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

    script

     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');
        }
      };
     }])
    
    0 讨论(0)
  • 2020-12-02 19:01

    For anything that has code that is triggered with a ng-click I just add a confirm attribute

    eg

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

    and confirm comes from (not mine, found on the web)

    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);
                    }
                }
            }
        })
    

    My google FOO has failed me and I cannot find the source site for this. I will update if I find it.

    0 讨论(0)
  • 2020-12-02 19:05

    so create a reusable service for that... read here

    code here:

    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 for display

    <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>
    

    once this is done... you just have to inject above service whereever you want to create a dialog box, example below

     $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
            });
    }
    
    0 讨论(0)
  • 2020-12-02 19:10

    You can create a simple factory like this

    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;
            }
    ]);
    

    In your controller

    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
     };
     }]);
    

    I have passed $scope in service function so that you can access closeModal function and in case you want to access some data from your controller . In your html

    <button ng-click="openModal()">Open Modal</button>
    
    0 讨论(0)
  • 2020-12-02 19:16

    You can use the Angular Confirm library.

    When included, it's became available as a directive:

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

    As well as a service:

    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...
            });
        };
      });
    
    0 讨论(0)
提交回复
热议问题