如何从AngularJS正确打开和关闭Bootstrap模态
How to properly open and close Bootstrap modal from AngularJS
在我的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">×</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):
- angular ui/bootstrap
- 角形带
两者都很好,所以使用对您的编码风格更舒适的库。
相关文章:
- 获取表单值并在提交时将其传递给Bootstrap模态
- Bootstrap模态主体:Json在上传Codeigniter后刷新
- Bootstrap 模态填充了相同的单个值 - Meteor+React
- Twitter Bootstrap 模态背景不会覆盖 iPad 上的整个屏幕
- ASP.NET Bootstrap 模态作为 JavaScript 确认
- AngularJS UI Bootstrap 模态无法从作用域执行函数
- React-Bootstrap 模态表单条目
- Bootstrap模态会在第二个打开模态时自动添加一个边距
- 将变量传递到Bootstrap模态中
- Bootstrap模态形式获胜't提交淘汰赛's提交绑定
- react bootstrap模态-我如何让它显示出来
- 使用jquery将多个items变量传递到Bootstrap模态中
- 隐藏Angular Bootstrap模态而不是关闭
- 如何从AngularJS正确打开和关闭Bootstrap模态
- 将图像和时尚文本传递到Bootstrap模态
- Bootstrap模态-打开元素的奇怪位置
- 修改默认值“;驳回“;Bootstrap模态的行为
- 将JSON数据加载到Bootstrap模态中
- 我如何通过javascript调用时传递数据到Bootstrap模态
- 模态体不会出现在bootstrap模态中