How can you merge the class attribute with the ng-class directive based on boolean values?

In my custom directive's link function, I have the following code that dynamically generates a map using d3...

map.append("g")
.selectAll("path")
.data(topojson.feature(counties, counties.objects.counties).features)
.enter()
.append("path")
.attr("d", geoPath)
.attr("class", function (d) { 
    return "county {{vm.showSalesAreas.data ? vm.getClass('" + d.properties.COUNTYFP + "') : ''}}"; 
})
.attr("ng-class", function (d) {
     return "{'active': vm.toggleActiveCountyFP == " + d.properties.COUNTYFP + ", 'highlight': vm.fipsList.data.indexOf('" + d.properties.COUNTYFP + "') > -1 && vm.showSalesAreas.data == false}";
})
.attr("id", function (d) {
    return d.properties.COUNTYFP;
})
.attr("tooltip-append-to-body", true)
.attr("uib-tooltip", function (d) {
    return d.properties.NAME;
})
.call(function () {
    $compile(this[0].parentNode)(scope);
});

Just to let you know, vm.salesAreas.data is actually a boolean value

I'm looking for a way to combine these two expressions into one in order to reduce the number of watchers. Any suggestions?

The issue I've encountered is that when I try to put the expression from the "class" .attr() into the ng-class attribute with 'classname' : boolean format, it doesn't seem to evaluate correctly because the classname comes from the vm.getClass() call. Any ideas on how to tackle this?

I attempted to use the line below, but even though vm.getClass() returns the correct class name and it is visible in the source inspection, the class fails to be applied...:

.attr("ng-class", function (d) {
    return "{'active': vm.toggleActiveCountyFP == " + d.properties.COUNTYFP + ", 'highlight': vm.fipsList.data.indexOf('" + d.properties.COUNTYFP + "') > -1 && vm.showSalesAreas.data == false, '{{::vm.getClass('" + d.properties.COUNTYFP + "')}}': vm.showSalesAreas.data, 'county': true}";
})

Answer №1

The statement below implies that all paths will be assigned the class "county".

enter()
.append("path")
.attr("d", geoPath)
.classed("county", true)//all paths will now have the class "county"
...

Within the link function, you can set up a watch to monitor changes and update the classes for the circle as follows.

$scope.$watch(DATA_WHICH_CHANGE,
              function() {
                  d3.selectAll(".county").classed("SOME_CLASS", YOUR_FUNCTION(d))
              }
             );

function YOUR_FUNCTION(d){
      //this function will return true or false based on the value of d (which is the data)
}

I believe this approach could help address your issue.

Hope this explanation is useful!

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

Retrieve information from two observables without the need for separate subscriptions

After my first observable emits user data from Firebase, I need to make a second call to retrieve additional user information from a different collection. While I can handle these operations separately, the second call should only be triggered once the fir ...

Should we fulfill the CSV Stringify promise in a test, or should we terminate the test when a function is invoked?

Currently, I'm attempting to simulate CSV Stringify using AngularJS, with the intention of extracting two parameters for future verification. My plan is to verify if certain options were correctly implemented later in the test. it("converts latitude ...

Get rid of all numbers from a jQuery selection except for the first and last

I am dealing with an array let numberArray = ["500", "600", "700", "800", "900", "1000", "1100", "1200"] My objective is to remove all elements except for the first and last ones. The challenge arises when the array contains only one value, as I must ens ...

Issue: The module could not be located within the project or in any of the directories, including node_modules

Error: It seems we're having trouble resolving the module navigation/stack-routes from MainTabs.tsx file in gymzoo project directory. The path navigation/stack-routes could not be located within the project or node_modules directory. Greetings! I&apo ...

Tips for Showing Certain Slides When the Page Loads

When using jQuery filter effects to organize div slides on a page, I encountered an issue where all the divs containing different slides are displayed on page load instead of just the default chosen ['active'] div. The filter effect itself is fun ...

How to dynamically add variables to object paths using JavaScript and Angular

I've been struggling to grasp this concept, despite hours of searching. My goal is to dynamically generate form fields based on a user-selected 'type' from a dropdown menu. This will be linked to the variable "currentType" in Angular, which ...

Increase the space below the footer on the Facebook page to allow for an

I recently created a webpage at and noticed that it is adding extra height below the footer on my Facebook page: "" I am seeking assistance on how to remove this additional 21px height below all content in the footer. I have tried various templates but n ...

Clear all CSS styles applied to a targeted division

My website built on Wordpress links to several CSS files. One specific div has its own unique style that is separate from the main Wordpress styles. Unfortunately, the Wordpress CSS ends up interfering with my custom div's layout. Is there a way in HT ...

Determining the time gap in milliseconds between two specified times using the "DD/MM/YYYY HH:mm:ss:ms" format in JavaScript

I have a situation where I need to calculate the time difference between two timestamps. Starting time: "2014/10/28 11:50:28:318" Ending time: "2014/10/28 11:50:35:249" To achieve this, I utilized moment.js for the calculation. Here is my code: var msE ...

What is the best way to refresh data in a React component so that it displays the recently added data?

My website features a todo list that functions like this: Todo list Upon clicking the plus button, an input field appears allowing users to add items. Although the item is successfully added to the database, it does not immediately reflect on the webpage ...

Ways to incorporate ejs partials using JavaScript

I am currently developing code to determine if a user is logged in. Depending on the user's login status, the content of the "my user" section should vary. When a logged-in user navigates to the "my user" page, an if statement is executed to confirm ...

When attempting to compile at runtime without an instance, the act of creating a function constructor can lead to an

My website is designed to function as a simple quiz game. It retrieves an array of JSON questions using AJAX, and for each question in the array, it displays the question itself along with buttons containing various options that were stored in the question ...

Efficiently handle file uploads utilizing FormData in AngularJS combined with Asp.Net MVC

My goal is to utilize AngularJS to upload multiple files, and I am implementing this using FormData(). Below are the form fields: <input name="profileImage" type="file" class="upload" onchange="angular.element(this).scope().LoadFileData(this.files)" a ...

Is it possible to create an index for an associative array based on a string in JavaScript?

Within my JavaScript code, I am working with an associative (two-dimensional) array (myObj[x][y]). Each row in this array contains a different number of elements denoted by 'n', where the first value signifies the amount 'n' as shown be ...

Is it possible to dynamically load JavaScript?

I'm currently working on a project that requires me to dynamically add JavaScript. I have a global.js file that contains all the global variables I need to add dynamically. However, I'm facing an issue where global.js is not being added before ut ...

In C#, transforming JSON serialization to replace single backslashes with double backslashes

When generating JSON to be included directly in an HTML file, it's important to wrap the JSON in a JavaScript string. For example: var dataContacts = '{"Contacts":[{"Id":0,"Active":false,"Company":"Rory The Architect\\, Melt"} ...

Guide on adding a button to a mat-table in Angular

I am looking to add a delete button or an Angular trash icon to a mat-table in an Angular application. Can anyone guide me on how to achieve this? Here is my current table code: <mat-table #table [dataSource]="ELEMENT_DATA"> <ng-container cdk ...

What is the best way to have react-bootstrap's Dropdown automatically open when hovering your mouse over it?

Looking for a simple solution. I want the dropdown to open when hovering over it, rather than clicking on it. Here is my current code: <Nav> <NavDropdown onMouseEnter = {()=> isOpen=true} open={isOpen} noCare ...

Is there a way to shift a background image pattern?

After searching extensively, I came up empty-handed and am seeking guidance on how to achieve a specific effect. Specifically, I am in need of a JavaScript or jQuery script that can smoothly shift a background image to the right within a designated div con ...

Using anti-cache code in jQuery's getJson function

During an interview, I was presented with the following question: Can you provide a one-liner code showing the proper syntax to add an anti-cache code to all jQuery getJson calls in a project without individually adding it to each call? I must admit th ...