3gwebtrain
3gwebtrain

Reputation: 15303

How to append `text` element by conditional in d3js

I would like to append the text node by conditional on my graphics. i am trying this, but not working.

what is the correct way to do that?

that.texts = that.groupElement.selectAll(label+"text").data(that.data).enter();

the approach is not working is here :

this.texts.append(function(d, i) {
            if(i== 0 && that.elementId === "paymentGraph")  {
                return "text" //so only one let created!
            }})
            .attr({
                class : this.elementId + "title"
            })
            .text("Total Contract Amount")
            .style("text-anchor", "middle");

The approach working is here : ( but I have 2 text node, 1 is empty)

this.texts.append("text") //adding 2 text element.
           .attr({
              class : this.elementId + "title"
          })
          .text(function(d,i) {
              if(i==0 && that.elementId === "paymentGraph") 
                 return "Total Contract Amount"; //only one required
          })
          .style("text-anchor", "middle");

Any one help me to showing correct way to append the node by conditional please?

Thanks in advance.

Upvotes: 1

Views: 4355

Answers (1)

Munick
Munick

Reputation: 461

append isn't where you want to make the condition.... append takes a node type and your function doesn't return anything half the time.

You should be using the selector to filter out what elements you want to append to and data for how many you want to append.

I think for you that would look something like

that.texts = that.groupElement.select("#paymentGraph")
             .selectAll(label+"text").data([that.data[0]]).enter();
this.texts.append("text")
.attr({class : this.elementId + "title"})
.text("Total Contract Amount")
.style("text-anchor", "middle");

or possibly

if(that.elementId === "paymentGraph") {    
    that.texts = that.groupElement.selectAll(label+"text").data([that.data[0]]).enter();
    this.texts.append("text")
    .attr({class : this.elementId + "title"})
    .text("Total Contract Amount")
    .style("text-anchor", "middle");
}

Upvotes: 2

Related Questions