如何在Angular中添加可重用的模态对话框?

Gen*_* S. 6 modal-dialog reusability angularjs

我是Angular的新手并试图将这个解决方案应用到我的项目中.

它看起来非常简单,但是,我试图将它变成一个可重用的元素,这样我就可以从任何地方调用它并只传入要显示的内容(否则,重点是什么?).

所以,我的具体问题是:假设我已经有一个controller绑定到某个DOM元素,并且它有一个功能可以获取一些factory驱动$http调用,并且响应我希望通过这个对话框通知用户,我该如何组合*这个指令和*这个控制器与我现有的一个,我怎么做的方式允许我从一个完全不同的方式再次使用它controller

或者这可能是这种用法的一个不好的例子,我应该看一个不同的?

Abr*_*ese 8

与其他选项相比,下面给出了极简主义的方法,使用角度工厂.请参阅下面的示例代码段.

注意:使用Angular JS和UI Bootstrap - AngularUI.

  1. 可重复使用的模态视图 - ConfirmationBox.html

<div class="modal-header">
  <h3 class="modal-title">{{title}}</h3>
</div>
<div class="modal-body">
  {{message}}
</div>
<div class="modal-footer">
  <button type="button" class="btn btn-primary btn-warn" data-ng-click="ok(); $event.stopPropagation()">OK</button>

  <button type="button" class="btn btn-default" data-ng-click="cancel(); $event.stopPropagation()">Cancel</button>
</div>
Run Code Online (Sandbox Code Playgroud)

  1. 可重复使用的模块和共享工厂,用于处理可重复使用的模态对话框

angular.module('sharedmodule',['ui.bootstrap', 'ui.bootstrap.tpls'])
.factory("sharedService",["$q", "$modal", function ($q, $modal)
{
    var _showConfirmDialog = function (title, message)
    {
        var defer = $q.defer();

        var modalInstance = $modal.open({
            animation: true,
            size: "sm",
            templateUrl: 'ConfirmationBox.html',
            controller: function ($scope, $modalInstance)
            {
                $scope.title = title;
                $scope.message = message;

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

                $scope.cancel = function ()
                {
                    $modalInstance.dismiss();
                    defer.reject();
                };
            }
        });

        return defer.promise;
    }

    return {

        showConfirmDialog: _showConfirmDialog
    };

}]);
Run Code Online (Sandbox Code Playgroud)

  1. 视图的一部分,使用共享模式对话框

<a data-ng-click="showConfirm()">Go Back to previous page</a>
Run Code Online (Sandbox Code Playgroud)

  1. 视图的控制器,打开共享的可重用模式对话框并处理通知(确定和取消)

var myModule = angular.module("mymodule", ['sharedmodule', 'ui.bootstrap', 'ui.bootstrap.tpls']);

myModule.controller('myController', ["$scope", "sharedService", "$window",
function ($scope, sharedService, $window)
{
    $scope.showConfirm = function ()
    {
        sharedService.showConfirmDialog(
            'Confirm!',
            'Any unsaved edit will be discarded. Are you sure to navigate back?')
            .then(function ()
            {
                $window.location = '#/';
            },
            function ()
            {
            });
    };
}]);
Run Code Online (Sandbox Code Playgroud)