You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让ng-repeat生成的Angular UI Bootstrap弹出框独立开闭

解决Angular UI Bootstrap ng-repeat生成的Popover同步开闭问题

这个问题我碰到过好多次啦——你现在所有的popover都绑定到了同一个dynamicPopover.isOpen变量上,相当于所有按钮共用同一个开关,自然会同时打开或关闭。要让它们独立控制,咱们只需要给每个循环出来的popover单独分配一个状态变量就行。

具体解决步骤:

  1. 重构控制器里的数据结构:
    不再用单个的dynamicPopover对象,而是为每个需要生成popover的项创建独立的配置。比如把原来的数组[1,2,3]改成包含每个项的状态和配置的数组,或者在控制器里初始化一个数组来存储每个popover的状态。

  2. 修改HTML中的绑定逻辑:
    ng-repeat时绑定到当前项的isOpen属性,而不是全局的dynamicPopover.isOpen。同时模板里的关闭按钮也要指向当前项的状态变量。

修改后的完整代码:

HTML部分:

<!doctype html>
<html ng-app="ui.bootstrap.demo">
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular-animate.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular-sanitize.js"></script>
<script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-2.5.0.js"></script>
<script src="example.js"></script>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div ng-controller="PopoverDemoCtrl">
<div style="padding-top:200px;"></div>
<!-- 现在循环的是popoverItems数组,每个item有自己的状态 -->
<button 
  ng-repeat="item in popoverItems" 
  uib-popover-template="item.templateUrl" 
  popover-title="{{item.title}}" 
  popover-is-open="item.isOpen" 
  type="button" 
  class="btn btn-default">
  Popover With Template {{item.id}}
</button>

<script type="text/ng-template" id="myPopoverTemplate.html">
<div>{{item.content.header}}</div>
<!-- 关闭按钮切换当前item的isOpen状态 -->
<button ng-click="item.isOpen = !item.isOpen">Close</button>
</script>
</div>
</body>
</html>

JS部分:

angular.module('ui.bootstrap.demo', ['ngAnimate', 'ngSanitize', 'ui.bootstrap']);
angular.module('ui.bootstrap.demo').controller('PopoverDemoCtrl', function ($scope, $sce) {
  $scope.content = { header: 'hello world' };
  
  // 初始化每个popover的独立配置
  $scope.popoverItems = [
    {
      id: 1,
      content: $scope.content,
      templateUrl: 'myPopoverTemplate.html',
      title: 'Title 1',
      isOpen: false
    },
    {
      id: 2,
      content: $scope.content,
      templateUrl: 'myPopoverTemplate.html',
      title: 'Title 2',
      isOpen: false
    },
    {
      id: 3,
      content: $scope.content,
      templateUrl: 'myPopoverTemplate.html',
      title: 'Title 3',
      isOpen: false
    }
  ];
});

为什么这样改能解决问题?

现在每个popover都绑定到了自己的item.isOpen变量上,它们的状态完全独立,不会再出现一个开关控制所有popover的情况。点击任意一个popover的按钮,只会切换当前这个popover的开闭状态,其他的不受影响。

内容的提问来源于stack exchange,提问作者Bryan Dellinger

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:22:12