过滤数据以有条件地呈现元素 [英] Filtering data to conditionally render elements

查看:169
本文介绍了过滤数据以有条件地呈现元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了这个SO - 过滤数据在d3中绘制圆形或正方形

I have come across this SO - Filter data in d3 to draw either circle or square

这是我要跟踪的,如果存在某个数据属性,试图有条件地呈现一些文本元素。

Which is what I'm following to attempt to conditionally render some text elements if a certain data property is present.

问题是,由于在追加后调用过滤器,因此上面帖子的接受答案导致添加了空元素。

The problem is that the accepted answer on the above post results in empty elements being added since the filter is being called after the append.

我尝试在附加调用之前过滤数据,如下所示:

I am trying to filter the data before the append call is made like so:

layers.selectAll('text')
    .data(function(d) {
        return d.dataPointValues;
    })
    .filter(function(d){
        return angular.isDefined(d.pointLabel);
    })
    .enter()
    .append('text')
    .text(function(d) {
        return d.pointLabel;
    })
    .attr('x', function(d) {
        return x(d.pointKey) + x.rangeBand() / 2;
    })
    .attr('y', function(d) {
        return y(d.y0 + d.pointValue) - 5;
    })
    .attr('class', 'data-value');

但我回到d3的错误:


TypeError:layers.selectAll(...)。data(...)。filter(...)。enter不是
函数

TypeError: layers.selectAll(...).data(...).filter(...).enter is not a function

如何使用过滤器只获取所需数量的文本元素,或者我应该使用不同的方法吗?

How can I get only the necessary number of text elements appended using a filter, or should I be using a different approach here?

推荐答案

您可以尝试对数据函数中的数据应用过滤器,如下所示:

You can try applying the filter on the data inside the data function like this

layers.selectAll('text')
.data(function(d){d.dataPointValues.filter(function(dp){ return angular.isDefined(dp.pointLabel); }})
.enter()
.append('text')
.text(function(d) {
    return d.pointLabel;
})
.attr('x', function(d) {
    return x(d.pointKey) + x.rangeBand() / 2;
})
.attr('y', function(d) {
    return y(d.y0 + d.pointValue) - 5;
})
.attr('class', 'data-value');

这篇关于过滤数据以有条件地呈现元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆