如何从AngularJS正确打开和关闭Bootstrap模态

How to properly open and close Bootstrap modal from AngularJS

本文关键字:Bootstrap 模态 AngularJS      更新时间:2023-09-26

在我的html页面上,我只得到了一个简单的Bootstrap模式和调用它的按钮:

        <button class="btn btn-primary" data-toggle="modal" data-target="#addUpdateGroup">Add group</button>
        <div class="modal fade" id="addUpdateGroup" tabindex="-1" role="dialog" aria-labelledby="addUpdateGrouplLabel" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                    </div>
                    <form name="addUpdateGroupForm" ng-submit="addUpdateGroupForm.$valid && groupCtrl.addUpdateGroup()" novalidate>                         
                        <div class="modal-body">
                                <input type="hidden" ng-model="groupCtrl.group.id" name="groupid" />
                                <label for="groupname">Group name:</label>
                                <br>
                                <input ng-model="groupCtrl.group.name" type="text" name="groupname" id="groupname" required />
                                <br><br>
                                <label for="groupcolor">Boja grupe:</label>
                        </div>
                        <div class="modal-footer">
                            <button type="submit" class="btn btn-primary">Add</button>
                            <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                        </div>
                    </form>                         
                </div>
            </div>
        </div>

这只是一个简单的表单。验证由AngularJS完成。

现在。。。当用户提交表单时,我希望模态关闭,但前提是它是有效的输入。

所以我把关闭模态的代码放进了控制器:

this.addUpdateGroup = function() {
    // Adding a new group
    if (typeof this.group.id === 'undefined') {
        this.id += 1;
        this.group.id = this.id;
        this.groups.push(this.group);
    // Updating an existing group
    } else {
        this.groups[this.group.id].name = this.group.name;
        this.groups[this.group.id].color = this.group.color;
    }
    // Clean the form and remove the modal
    this.group = {};
    $scope.addUpdateGroupForm.$setPristine(true);
    $('.modal').modal('hide');
};

但这并没有遵循不从控制器操作DOM的最佳实践。

问:有更好的方法吗?当调用控制器中的某个函数时,您将如何实现需要显示或隐藏的模式?

您没有遵循Angular的最佳实践。如果你还没有这么做,请回顾这个传奇的答案:https://stackoverflow.com/a/15012542/202913特别是该帖子的第1-3点。

顺便说一下,您应该使用以下两个库中的任何一个。它们都实现了Bootstrap的功能,但使用了原生的Angular实现,即它不依赖于Bootstrap中的Javascript库(但使用了BootstrapCSS):

  1. angular ui/bootstrap
  2. 角形带

两者都很好,所以使用对您的编码风格更舒适的库。