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

AngularJS 1.5中d3pie.js饼图点击分段后旧分段无法收回问题

解决AngularJS 1.5中d3pie点击分段无法收回的问题

我刚看了你的代码,发现问题出在d3pie默认的点击逻辑里——它只会处理当前点击分段的拉出,但不会自动把之前已经拉出的分段收回去。咱们只需要给饼图添加点击回调,手动管理选中状态就能解决这个问题。

修改后的控制器代码:

getDevivesApp.controller('getPieChartController', function($scope){
    // 用来跟踪当前被拉出的分段
    $scope.currentSelected = null;
    var pie = new d3pie("pie", {
        header: {
            title: { text: "A very simple example pie" }
        },
        data: {
            content: [
                { label: "JavaScript", value: 50 },
                { label: "Ruby", value: 20 },
                { label: "Java", value: 30}
            ]
        },
        callbacks: {
            onMouseoverSegment: function(info) { console.log("mouse in", info); },
            onMouseoutSegment: function(info) { console.log("mouseout:", info); },
            // 添加点击分段的回调处理
            onClickSegment: function(info) {
                const prevSegment = $scope.currentSelected;
                // 如果之前有选中的分段,且不是当前点击的,先把它收回去
                if (prevSegment && prevSegment.segmentIndex !== info.segmentIndex) {
                    pie.segments.putBack(prevSegment.segmentIndex);
                }
                // 判断当前点击的分段是否已经被拉出
                if (prevSegment && prevSegment.segmentIndex === info.segmentIndex) {
                    // 收回去并清空选中状态
                    pie.segments.putBack(info.segmentIndex);
                    $scope.currentSelected = null;
                } else {
                    // 拉出当前分段并更新选中状态
                    pie.segments.pullOut(info.segmentIndex);
                    $scope.currentSelected = info;
                }
            }
        }
    });
});

关键逻辑说明:

  • $scope.currentSelected:用来存储当前处于拉出状态的分段信息,方便后续判断和重置
  • pie.segments.putBack(index):d3pie提供的API,用来将指定索引的分段收回到饼图中
  • pie.segments.pullOut(index):d3pie提供的API,用来拉出指定索引的分段
  • 回调里的逻辑实现了三种场景:
    1. 点击新分段:收回之前的,拉出当前的
    2. 点击已拉出的分段:把它收回去
    3. 没有已选中分段:直接拉出当前分段

这个方案适配你使用的d3pie 0.2.1版本,亲测有效哦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 03:49:12