Analyzing two arrays and utilizing ng-style to highlight matching entries within the arrays

My list displays words queried from a database, allowing me to click on a word to add it to another list that I can save. This functionality enables me to create multiple word lists. My goal is to visually distinguish the words in my query list that have already been added to the new list by giving them a different color.

To achieve this, I utilize a function in my controller that uses angular.foreach to compare the two lists. If wordFromQuery._id === wordOnNewList._id, I change the background color of the word using ng-style.

Below is the code snippet:

View

ng-repeat="word in searchWords" ng-click="addWordToSet(word)" ng-class="isInside(word)" ng-style="{ background: choosenWords.value == 'exist' ? 'lightgreen' : 'white' }"

I iterate over the words in the query (searchWords) and add them to the second array using addWordtoSet(word) function. The isInside(word) function performs the comparison between the arrays, while ng-style applies different styles based on the outcome of the isInside function.

Controller

    $scope.isInside = function (word) {
      angular.forEach($scope.currentWordlist, function (item) {
        if (item._id === word._id) {
          $scope.choosenWords = {value: 'exist'};
        } else {
          $scope.choosenWords = {value: 'notOnList'};
        }
       });
    };

The angular.forEach method compares the words in both arrays. currentWordList is where I store the words added using addWordToSet function.

Currently, one word in the searchword array receives the green color when clicked (and the next word will be highlighted as well). It seems like there might be an issue with how I'm using ng-class, but I haven't found a better alternative for accessing the word._id. Can someone point out any obvious mistakes in my approach?

If anyone has any tips or suggestions, I would greatly appreciate it. Thank you!

UPDATE

The addWordToSet function works as intended:

      $scope.addWordToSet = function (word) {
        var exists = false;
        angular.forEach($scope.currentWordlist, function (item) {
          if (item._id === word._id) {
          exists = true;
        }
      });
        if (!exists) {
          $scope.currentWordlist.push(word);
        }
      };

My only concern now is triggering this behavior without requiring a click. Is my ng-class="isInside(word)" suitable for achieving this automatic update?

Answer №1

One way to incorporate a specific color into a variable within the same function and utilize it in the visual representation.

$scope.isInside = function (word) {
  angular.forEach($scope.currentWordlist, function (item) {
    if (item._id === word._id) {
      $scope.choosenWords = {value: 'exist'};
      $scope.color = 'lightgreen'
    } else {
      $scope.choosenWords = {value: 'notOnList'};
      $scope.color = 'white'
    }
   });
};

ng-style="{'background-color':color}"

Visual Representation:

ng-repeat="word in searchWords" ng-click="addWordToSet(word)" ng-class="isInside(word)" ng-style="{'background-color':color}" }"

Answer №2

Give it a shot

$scope.chosenWords = {value: 'exist'};

Make sure to initialize chosenWords at the beginning of your controller.

If the above solution doesn't solve the issue, review the execution order of ng modules in your code.

Is the controller being initialized through a partial?

Answer №3

Collaborating with a friend, we were able to solve this issue and came up with a functional solution. In case anyone encounters a similar problem, here is how we tackled it:

Within the Controller, we implemented the following function:

    $scope.isSelected = function (word) {
      var found = false;
      angular.forEach($scope.currentWordlist, function (item) {
        if (item._id === word._id) {
          found = true;
        }
      });
    return found;
    };

This function utilizes a forEach loop to compare arrays and set a boolean flag based on matching IDs.

For the View, we utilized the following snippet:

ng-class="isSelected(word) ? 'marked' : 'unmarked'"

This code applies a CSS class (either "marked" or "unmarked") to style the matched words in green and all other words in white background color.

Below is the corresponding CSS:

.marked {
  background: $lightgreen;
}

.unmarked {
  background: $nicewhite;
}

While I personally used SCSS and color variables, any colors can be substituted accordingly. This approach resulted in two viewable arrays - one displaying all words retrieved from a database query, and another showcasing user-selected words highlighted in green upon clicking. That's the gist of it; hopefully, this information proves helpful!

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

Utilizing Vue.js to Showcase Real-Time Data on an HTML Page

I am attempting to showcase the bill structure on an HTML page by retrieving data in Vue and Axios. There is a table where orders are listed, with each row having a "Print" button. When this button is clicked, I want to display the specific order details i ...

What is the most effective way to showcase a list of image URLs in HTML with Vue?

Currently, I am working with an array called thumbnails that holds the paths to various images. My goal is to use masonry in Vue to arrange these images in a grid format, but I'm encountering some difficulties achieving the desired outcome. This is m ...

Three.js: Objects in the distance appear more subtle

Currently, I am developing a three.js scenario that showcases textured point sprites. These sprites obtain their textures from a single uniform, which is a 2D canvas containing the alphabet: https://i.stack.imgur.com/Ceh9x.png In my scene, all the letter ...

Text randomly appears on the html page

I've been dedicating a significant amount of time to finding a solution, but haven't had any luck. I'm aiming to create a visual effect where 10 words with varying font sizes slide in from different directions on a canvas within my document ...

Inserting an HTML element into Handlebars.js during a specific iteration of an each loop

I have a channel.json file containing 7 objects of data which are iterated in hb. I am looking for a way to insert a date between these iterations without modifying the .json file. How can I add an html tag to display after the 3rd iteration within the loo ...

Issue: ENOENT - The specified file or directory cannot be found while scanning in a discord bot

Recently, I decided to try my hand at creating discord bots even though I am new to it. After watching a tutorial and copying the code, I encountered an error that has me stumped: node:internal/fs/utils:347 throw err; ^ Error: ENOENT: no such ...

What is the procedure for automatically playing the next audio track in HTML5 after the current one finishes playing

When trying to play a single MP3 file, the code below is designed to skip to a specific part of the track and then start playing from that position. However, despite the cursor moving to the correct spot in the MP3, it fails to play upon clicking the Sta ...

Sending data from $routeProvider to the View

How can I send a variable from $routeProvider to a view file: app.config(['$routeProvider', function ($routeProvider) { $routeProvider .when('/send-money', { templateUrl: 'partials/send-money.html', controll ...

Where is the best place to insert Javascript code in an HTML file - the head or body section?

I am currently developing a search engine and have implemented code to automatically redirect users from HTTP to HTTPS when they visit my site. The only question I have is whether I should place this code in the head or body section of my webpage. if(wind ...

What is the best way to invoke my Python function within my JavaScript file?

I am facing an issue with using my Python function in JavaScript. Although the actual code I am working on is more complex, I have simplified it to demonstrate the problem below: main.mjs dbutils.notebook.run("./aPythonFile.py", 5, {"parame ...

Learn the process of retrieving JSON objects through AJAX using jQuery

When making a jQuery call to an API website, I receive the results in JSON format: { "results":[ { "user":{ "gender":"female", "name":{ "title":"mrs", "first":"linda", "last":"diaz" }, ...

Applying an angular filter to a string parameter within an ng-click function

I have created a custom angular filter directive that allows for string replacement using the syntax below: {{ 'MyValue' | replace: 'My':'Foo' }} This functionality works perfectly. Now, I am trying to use this filter within ...

Obtaining an XML element within an XSLT transformation

I need to retrieve the value of an XML element within XSL. Although my JavaScript is able to select one XML document, there are elements in other documents that I also require. I am uncertain if this task is feasible or if my syntax is incorrect. This is ...

Is your Z-Index failing to make an impact?

Currently, I am attempting to layer divs on top of a background image. All the elements have designated position attributes, and I have applied a 50% opacity to the background image so that what's behind it is partially visible. Despite setting the z- ...

User interaction with a checkbox triggers a state change in Angular

Here is the code snippet I am working with, where clicking should set the checked value to false: @Component({ template: ` <input type="checkbox" [checked]="checked" (change)="onChange()"> ` }) export class AppC ...

Eliminate the CSS triggered by a mouse click

Having some difficulty toggling the switch to change the background color. Struggling with removing the applied CSS and getting it to toggle between two different colored backgrounds. Code Sample: <!Doctype html> <html lang="en"> <head> ...

Animate sliding bar to move from the left using jQuery

I am currently experiencing an issue with a sliding animation on mouseover in the navigation. The animation works fine, but the problem arises when I hover over any menu item - the sliding bar starts from the very left instead of starting where the navigat ...

Purge stored events from BehaviorSubject in Angular2 using Observables as they are consumed

I'm encountering an issue that I believe stems from my limited understanding of Observables. This project is built on Angular2 (v4.0.3) and employs rx/js along with Observables. Within a state service, there exists a store for events: // Observab ...

When using React, the event.target method may unexpectedly return the innerText of a previously clicked element instead of the intended element that was

I have implemented a drop-down menu that triggers an event handler to return the selected option when it is clicked. Upon clicking on an option, I retrieve the inner text of that option using the event. The code snippet looks like this: event.target.inner ...

Is it time to advance to the next input field when reaching the maxLength?

In my Vue form, I have designed a combined input field for entering a phone number for styling purposes. The issue I am facing is that the user needs to press the tab key to move to the next input field of the phone number. Is there a way to automaticall ...