gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 13:50:09 25 4
gpt4 key购买 nike

我是 Angular 新手,正在尝试实现 this solution进入我的项目。

它看起来很容易,但是,我试图将它变成一个可重用的元素,以便我可以从任何地方调用它并传入要显示的内容(否则,有什么意义?)。

所以,我的具体问题是:假设我已经有一个 controller绑定(bind)到一些 DOM 元素,它有一个特性可以获取一些 factory驱动 $http调用并根据响应我希望通过此对话框通知用户某事,我如何将 *this 指令和 *this Controller 与我现有的 Controller 结合起来,以及如何以一种允许我再次使用它的方式进行操作一个完全不同的controller ?

或者这可能是这个用途的一个坏例子,我应该看一个不同的例子吗?

最佳答案

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

备注 :使用 Angular JS 和 UI Bootstrap - AngularUI。

  • 可重复使用的模态视图 - 确认框.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>


  • 可重用模块和共享工厂,用于处理可重用模态对话框


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

    }]);


  • View 的一部分,使用共享模式对话框


  • <a data-ng-click="showConfirm()">Go Back to previous page</a>


  • View Controller ,打开共享的可重用模式对话框并处理通知(确定和取消)


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

    关于angularjs - 如何在 Angular 中添加可重用的模态对话框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25341798/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com