【问题标题】:Create a simple Bootstrap Yes/No confirmation or just notification alert in AngularJS在 AngularJS 中创建一个简单的引导是/否确认或只是通知警报
【发布时间】:2015-06-18 13:55:40
【问题描述】:

在非 Angular 环境中它是如此简单。只需 html 和两行 js 代码即可在屏幕上显示模态确认对话框。

现在我正在开发一个 AngularJS 项目,在该项目中我到处使用 ui-bootstrap 模式确认对话框,我厌倦了创建新控制器,即使是“你确定要删除这条记录吗?”这样简单的事情。那种东西。

您如何处理这些简单的情况?我相信有些人写了一些指令来简化需求。

我要求您分享您的经验或您对该主题了解的项目。

【问题讨论】:

  • @Chandermani 看起来不错。现在正在浏览文档,谢谢!
  • @Chandermani 该实现还需要创建一个无法满足我需求的额外控制器。
  • 查看 v1 codepen codepen.io/m-e-conroy/pen/rkIqv,对于类型错误的对话框,通知并确认
  • @Chandermani,错过了那个,我现在明白你的意思了:)

标签: angularjs angular-ui-bootstrap bootstrap-modal


【解决方案1】:

为此创建一个可重用的服务...read 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

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

【讨论】:

  • 这看起来像是一种在全局范围内使用对话框的优雅方式。在我为此尝试之前,将等待其他答案,然后再接受您的答案。谢谢!
  • 给我你的问题的链接,将把必要的代码作为答案
  • 为了能够使用此模式,必须执行以下操作: 1. 在 index.html 中加载 ui-bootstrap-0.14.3.js(或适当的文件版本) 2. 将 ui.bootstrap 声明为应用程序,如下所示:angular.module('testApp', ['ui.bootstrap']);。如果包含最新版本,则在上述模态服务代码中,将$modal 替换为$uibModal,将$modalInstance 替换为$uibModalInstance
  • 有人在uglify后遇到未知提供者aProvider的问题吗?
  • 在代码中执行此行后在控制台中显示此错误消息:return $modal.open(tempModalDefaults).result;错误:未知提供者:aProvider
【解决方案2】:

你可以看看我的例子。不管我做了什么。

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

【讨论】:

  • 我猜你错过了“Bootstrap Modal Dialogs”部分 :) 谢谢你的回答,不过......
【解决方案3】:

你可以像这样创建一个简单的工厂

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

我已经在服务函数中传递了$scope,这样你就可以访问 closeModal 函数,以防你想从你的控制器访问一些数据。 在你的 html 中

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

【讨论】:

  • @entre 建议的简化版本。感谢您的回答。
  • 如果我在确认模式窗口中单击“是”或“否”,该解决方案将如何处理?
【解决方案4】:

对于任何具有通过 ng-click 触发的代码的内容,我只需添加一个确认属性

例如

<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 的新手,我发现有很多方法可以做事,我选择了这个,因为我喜欢你只有一个属性并且你去的事实,你也可以有一个返回布尔值的 confirmif 属性。
【解决方案5】:

您可以使用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...
        });
    };
  });

【讨论】:

  • 谢谢!很高兴知道:)
  • 链接失效
  • 感谢@walla,已修复!
猜你喜欢
  • 2014-07-28
  • 1970-01-01
  • 2017-10-12
  • 2011-06-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-11
  • 1970-01-01
相关资源
最近更新 更多