anoop chandran anoop chandran - 1 month ago 6
Javascript Question

Insert and remove Expression into div on button click

I have created a heatmap using Kendo UI and Angular. This is the code.

<div id="heatMapCell" data-value="{{params.compare ? h.percentChange : h.current[unit]}}"></div>


and this is the result..

enter image description here
Now here is another variation of the heatmap. Code..

<div id="heatMapCell" data-value="{{params.compare ? h.percentChange : h.current[unit]}}">
{{params.compare ? h.percentChange : h.current[unit]}}
</div>


which renders like this..
enter image description here
All i did was, insert the expression of
data-value
inside the
div
. So what I'm trying to achieve here is introduce a button(
#numberBtn
) that says "Show Numbers" and when user clicks on it, it will show the heatmap with the numbers in it. Also when user clicks the button again the numbers would be removed. So my understanding is that on button clicks i need to insert/remove the
{{params.compare ? h.percentChange : h.current[unit]}}
to/from the
div
.
I have a button click function like this..

$('#numberBtn').click(function() {
if ($(this).hasClass('active')) {
$(this).removeClass('active');
$( "#numberCells" ).remove(); //Remove expression here
} else {
$(this).addClass('active');
$( "#heatMapCell" ).append( "<div id='numberCells'>{{params.compare ? h.percentChange : h.current[unit]}}</div>" ); // Add expression here
}
$('#numberBtn').toggle();
});


This code is working and partially achieves what i want. Only problem is the expression is get rendered as string, not actual data. Like this...

enter image description here

So my question is How to insert/remove an expression to a div.. using jquery or javascript or Angular? I'm not sure but I think, maybe, i need to refresh/setTimeout the heat-map, so it get rendered with new added expression. So my second question, if i wanted to refresh/reload just the div, How should I do it? Suggestions are welcome.

2ps 2ps
Answer

I would just do this with CSS so that you don’t have to rerun $compile.

<div id="heatMapCell" data-value="{{params.compare ? h.percentChange : h.current[unit]}}">
    <span class="heat-map-number">{{params.compare ? h.percentChange : h.current[unit]}}</span>
</div>

Then you can just add/show those elements using jQuery:

$('#numberBtn').click(function() {        
    if ($(this).hasClass('active')) {
        $(this).removeClass('active');
        $( ".heat-map-number" ).hide();
    } else {
        $(this).addClass('active');
        $(".heat-map-number").show();
    }
    $('#numberBtn').toggle();
});

Adding, if you want to be an angular purist, you can also do this with ngShow or ngHide and using a scope variable that gets toggled on the button click.

Comments