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

Having trouble accessing the dashboard after uploading a document to Firestore

I am currently working on a project where I need to upload an audio file to Firebase storage and also add document data related to the audio file in Firestore database. The process involves recording the audio, uploading it to Firebase storage, submitting ...

What is preventing my code from locating the AngularJS $interval functionality?

Having an issue with my AngularJS Code when trying to call $interval in VS2013. The error message says it is not found. Here's the code snippet: var appRun = [ '$rootScope', function ( $rootScope ) { // This ...

JavaScript Grouping Arrays

I am working with an array and need to filter it by both Country and Service. So far, I have successfully filtered the array by Country. Now, I want to achieve the same filtering process based on the Service as well. Here is a snippet of the array: [ ...

Tips for efficient navigation through posts when they are loaded via a JSON file

Check out my Plnkr demo: http://plnkr.co/edit/brWn6r4UvLnNY5gcFF2X?p=preview Let's say I have a JSON file: { "info": { "test1": "test", "teste2": "test" }, "posts": [ { "name": "lorem ipsum", "content": "sit a ...

Retrieve a comprehensive inventory of all routes within a Vue project and automatically create a sitemap for the website - Vue Project

Imagine I've set up a route like this: import Vue from "vue"; import Router from " vue-router"; import BookRoutes from "./routes/book"; Vue.use(Router) const router = new Router({ routes:[ { path ...

Steps for extracting URL parameters from AWS API Gateway and passing them to a lambda function

After successfully setting up my API gateway and connecting it to my lambda function, I specified the URL as {id} with the intention of passing this parameter into the lambda. Despite numerous attempts using both the default template and a custom one for ...

Unexpected memory leaks with ionic during push notification setup leading to system slowdown

Lately, I've been encountering some unusual memory problems that have been persisting for a few days. The issue arises when the app gets stuck and starts rapidly consuming memory until it eventually crashes. During this memory spike, the entire app f ...

Enabling and disabling contenteditable functionality on a div element in Angular

Issue I am facing an issue while trying to bind a boolean to the contenteditable directive of a div. However, it seems that this binding is not working as expected. Error Message: The 'contenteditable' property is not recognized as a valid p ...

Unleashing the Power of Conditional HTML Attribute Insertion

What is the best way to add a conditional attribute in AngularJS? For instance, I am looking to only apply the multiple attribute to a <select> element if a certain binding in my component is set to true. If this binding is not present, then the mul ...

Utilizing Vue: Attaching click event to dynamically added elements

I am working on a Vue application that retrieves HTML content from an API. This HTML contains blocks with the class <div class="play-video">...</div> Using axios to call the API and a promise, I insert the content into the DOM like this: < ...

Issue Alert: Inconsistencies with Google Scripts spreadsheets

Objective I have been working on a script that will make consecutive calls to an API (with a JSON response) and input the data into a Spreadsheet. Issue: When I debug the script, everything runs smoothly without any major problems. However, when I try r ...

Repairing the Performance of the 'Save' Feature

Can the 'Save' button in my code save team assignments for players selected using drag and drop? I'm considering using localStorage, but unsure about implementation. Note: To run the code properly, copy it as an HTML file on your computer. ...

include a button next to the input field

As you reduce the browser window size, you may notice a different layout designed specifically for iPhone. One question that arises is how to add a button next to the search text box dynamically using JavaScript. The issue at hand is that the text box is b ...

Choose a specific 24-hour range with the Date Interval Selector

I am currently utilizing the Date Range Picker plugin for bootstrap from the website http://www.daterangepicker.com/#examples, and I have a requirement to set the maximum date time range to be within 24 hours. Below is an example demonstrating how I can s ...

Navigating through multiple pages with React Native stack navigation

I'm currently in the process of developing a react native app and I'm facing some confusion with regards to page navigation. It appears that there is a glitch in the navigation flow, causing it to skip a page. <NavigationContainer> ...

In what ways can we utilize a consistent state across various tabs or pages?

One feature of my application is a dynamic chart with various settings such as filters and time ranges. I want to save these settings in the app's state so they can be shared with other components on different pages. However, when switching tabs and r ...

Bower encountered difficulty in locating a compatible version for angular

Thank you for taking the time. I'm facing an issue where I am "Unable to find a suitable version for angular" and I'm feeling overwhelmed with the options. If you were in my position, what would be your course of action? Here is the content of ...

When using Google Maps Autocomplete, always make sure to input the full state name instead of just the state

Utilizing the Google Maps autocomplete API, we have enabled our customers to search for locations in the format of city, state, country. The functionality is effective overall, but a recurring issue arises when searching for cities, such as 'Toronto&a ...

Retrieve DirectionsResult data from a Google Maps URL

Currently, I am developing an updated tool that can transform Google Maps directions into GPX files. The initial version of this tool is performing quite well: it utilizes the Google Maps Javascript API (v3) to showcase a map on the website, allowing users ...

How can you correctly make an Ajax request using computed properties sourced from VueX Store?

Is there a way to make an AJAX call where one of the parameters is a computed State in VueX? For instance, if I use this.$axios.get('someUrl/' + accID ), with accID being a computed property from VueX (using MapState), sometimes it returns ' ...