Leveraging the power of Angular's ng-class directive in conjunction with d3.js on

Struggling to implement the angular ng-class directive with the d3js library within an svg element without success.

HTML

<div ng-controller="MainCtrl">

  <div id="svgContainer"></div>
  <button id="swicthBtn" ng-click="switchStatus();" class="btn">Switch status</button>

</div>

CSS

*, *:before, *:after {
  bounding-box: border-box;
}

#svgContainer {
  width: 400px;
  height: 400px;
  background-color: #333;
}

.btn {
  margin: 1em;
  padding: 1em;
}

.active {
  fill: red;
}

.inactive {
  fill: #666;
}

JS

var app = angular.module("myApp", []);

app.controller("MainCtrl", ["$scope", function($scope) {

    $scope.status = true;
  $scope.switchStatus = function() {
    $scope.status = !$scope.status;
  }

  var svg = d3.select("#svgContainer").append("svg")
    .attr("width", 400)
    .attr("height", 400);

  var rect = svg.append("rect")
    .attr("x", 150)
    .attr("y", 150)
    .attr("width", 100)
    .attr("height", 100)
    .attr("ng-class", "status ? 'active' : 'inactive'");

}]);

Check out the code on jsfiddle. There are 2 CSS classes, active and inactive, that should be assigned to the svg rectangle dynamically based on the value of the $scope.status variable. Unfortunately, it's not working. I've tried different variations of the ng-class expression like:

"{status ? 'active' : 'inactive'}" 

or

"{'status' ? 'active' : 'inactive'}" 

but none have been successful.

Is it possible that the ng-class directive is not supported on svg elements or am I missing something?

Answer №1

If you are attempting to utilize ng-class as an attribute without running it through angular first, it will not work properly.

Angular does not automatically recognize this attribute. To resolve this issue, you must execute $compile(svg)($scope) on the generated svg in order for angular to function correctly.

$compile Angular Service

Ensure that you invoke angular on the dom element and not on the wrapped d3 element.

JS Fiddle with functioning code

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can one retrieve data from two distinct API routes within a Next.js application?

Currently, I am working with Next.js and facing a challenge in fetching data from two different API routes simultaneously. My intention is to retrieve this data within the getServerSideProps function. The first dataset that I require can be found at the e ...

Issues with Fetch API and CORS in Web Browsers

Hello, I'm encountering an issue related to CORS and the Fetch API when using browsers. Currently, my setup involves running a NodeJS server built with Express on localhost:5000. This server responds to a GET request made to the URL /get_a, serving ...

Craft a brief description for every individual component discovered

Is there a way to identify and shorten all elements containing a <tspan> tag to just ten characters each? For example: <tspan>Bla bla bla bla</tspan> <tspan>Bla bla bla bla</tspan> <tspan>Bla bla bla bla</tspan> ...

evt.target consistently returns the initial input within the list of inputs

My React file uploader allows users to attach multiple file attachments. Each time a user clicks on an input, I retrieve the data-index to identify the input position. renderFileUploader() { let file_attachment = this.state.file_attachment.map(fun ...

What is the best way to extract the src attribute from an image tag nested within innerHtml?

In the developer tools, navigate to console and enter: var x= document.getElementsByClassName('ad-area')[0].innerHTML; x returns: '<a href="/members/spotlight/311"><img class="block-banner" src="https://tes ...

Can you explain the functionality of this particular line of code in JavaScript?

As I continue to practice my coding skills, despite still being relatively new, I often come across this type of code in loops when searching for solutions to practice problems. I am intrigued by what exactly this particular line of code is accomplishing. ...

What's the best way to execute multiple actions within a single gulp task?

Is there a way to execute multiple actions within one gulp task? I have tried using event-stream's merge feature following the example in How to perform multiple gulp commands in one task, but it doesn't work properly when combined with the del p ...

Monitor the fullscreenChange event with angularJs

Utilizing a button to activate fullscreen mode for a DOM element using the fullscreen API is functioning correctly. The challenge arises when exiting fullscreen mode, requiring the listening for the fullscreen change event in order to resize the DOM elemen ...

The Angular app.component.html is failing to display the newly added component

Having some trouble rendering my new component in the browser. I've set up a fresh project using the Angular CLI and created a component named list-employees. Upon running ng serve -o, the project compiles without errors, but the browser displays a b ...

AngularJS: Removing elements from scope array causes ng-view to disappear completely

In my AngularJS application, I have a $scope array that populates a ul with li elements. Each li has an "x" which, when clicked, triggers a function in my Chatroom controller to remove the item from the $scope array. The expected behavior is for the item ...

Unable to get the deletion functionality to work for Dropzone.js and PHP script

I am currently using dropzone to handle file uploads. My goal is to delete the files on the server when the user clicks on the removeLink. I have implemented an Ajax function that calls a .php site for this purpose. However, I am facing an issue where I am ...

Revise the validation process for the drop-down menu and input field

Looking for help with text field validation based on a dropdown selection. There are two scenarios to consider: 1. User changes dropdown value and then enters text in the field. 2. User enters text in field and then changes dropdown. I've written cod ...

Is there a way to integrate AngularJS with XAMPP for server communication without utilizing Node.js?

I've been using XAMPP for my programming web applications, primarily with PHP. However, I've now made the switch to AngularJS. The problem is, I can't seem to find any tutorials on server communication without Node.js Since I'm not co ...

Guide to rendering pages in SSR mode in NextJS on a specific environment and serving static pages on a different environment

I am facing a challenge with my setup where I have a Strapi backend deployed on the environment I manage, and a NextJS frontend hosted on Vercel. On the other hand, my client has the same Strapi backend code running on Google Cloud and the frontend code ho ...

Acquiring information from a variable via an HTTP request

I am new to making http requests and using PHP. I have a code snippet that makes an AJAX call: xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var doc = xmlhttp.response; myFunc( ...

Is it possible to develop a web browser application using Ionic framework?

Can Ionic be used to create a web browser app similar to Cake Web Browser (https://itunes.apple.com/us/app/cake-web-browser/id1163553130?mt=8)? Below is the code I have, but I am encountering the following error... "Refused to display document because di ...

There are three checkboxes, one of which is independent of the others and requires jQuery to not consider it part of the collection

Initially, I crafted a query that perfectly met the business requirement until there was a change of heart. Uncheck checkbox if checked with jquery The implementation of this code was flawless $('input[type="checkbox"]').on('change' ...

I am experiencing an issue with my Node.js query, as it is not successfully adding a user to my database using

I'm currently working on developing an API using Node.JS, express, and MySQL with the Sequelize ORM. I wanted to do this project properly without relying on the CLI for every task. However, I've encountered a problem where my API fails to create ...

Guidelines for accessing a specific object or index from a dropdown list filled with objects stored in an array

Here is a question for beginners. Please be kind. I have created a select field in an HTML component using Angular, populated from an array of objects. My goal is to retrieve the selection using a method. However, I am facing an issue where I cannot use ...

JavaScript Recursive Function for Generating FancyTree JSON Structure

I'm currently building an array of JSON objects for FancyTree (https://github.com/mar10/fancytree/wiki/TutorialLoadData). My JSON source is from the Jira REST service, and its structure can vary widely. Therefore, the code to construct the array of JS ...