Examining the Similarities Between Two Arrays using ng-repeat

I am attempting to generate multiple checkboxes using ng-repeat from Array1, and I want to apply the "checked" attribute (using ng-checked) to specific checkboxes based on whether there is a match in Array2.

Here are the elements in array1 within the controller:

$scope.possibleConditions = ["condition1", "condition2", "condition3", "condition4"];

And array2 is retrieved from the same controller but through a JSON API.

{
    "treated" : false,
    "data" : [{
        "conditions" : ["condition1", "condition2"],
    }]
}

This is how I currently have my ng-repeat set up in the template:

<p ng-repeat="condition in possibleConditions">                     
    <input type="checkbox" id="{{condition}}" />
    <label for="{{condition}}">
        {{condition}}
    </label>            
</p>

The goal is to include the checked attribute on the checkbox if a particular condition, such as "condition1" from Array1, is found in the "conditions" array of Array2.


What I have attempted so far:

1: I tried utilizing a filter (discovered on stackoverflow) after defining my controller:

.filter('customArray', function($filter){
return function(list, arrayFilter, element){
    if(arrayFilter){
        return $filter("filter")(list, function(listItem){
            return arrayFilter.indexOf(listItem[element]) != -1;
        });
    }
};

I adjusted the ng-repeat slightly like this:

<p ng-repeat="conditions in possibleConditions | customArray:profileData.data:'conditions' ">

However, that approach did not work as expected.

2: Another attempt involved nesting another ng-repeat within the original one, then comparing against the first iteration for a match.

Sample snippet:

<p ng-repeat="conditions in possibleConditions">                    
    <input ng-repeat="condition in profileData.data[0].conditions | filter{condition == conditions}" type="checkbox" id="{{condition}}" />
    <label ng-repeat="condition in profileData.data[0].conditions | filter{condition == conditions}"  for="{{condition}}">
        {{condition}}
    </label>            
</p>

I am hopeful that someone can provide assistance or guidance. Thank you.

Answer №1

To avoid using a filter in this scenario, consider implementing the ngChecked directive:

<p ng-repeat="condition in possibleConditions">
  <input type="checkbox" id="{{condition}}" 
         ng-checked="response.data[0].conditions.indexOf(condition) > -1" />
  <label for="{{condition}}">
    {{condition}}
  </label>
</p>

Check out the live demo here: http://plnkr.co/edit/fDn0niCCljo5wChzYiwa?p=info

Make sure to replace response with your actual API data.

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

The JSON.stringify function is returning inaccurate index structures

https://i.sstatic.net/ptMcW.png I am attempting to use the JSON.stringify() method on my object (refer to the screenshot). However, the result I am getting is not what I expected - the indexes of the objects are in the wrong order. You can view the comp ...

Link a distinctive number to a specific element

I am searching for a method to link a DOM element with a distinct number that is not assigned to any other element in the DOM. Using an Id attribute is not an option as not all elements possess such an identifier. One potential approach is to obtain a num ...

What's the Deal with Blank Square Brackets in JavaScript?

While browsing through , I stumbled upon this code snippet: useEffect(() => { const interval = setInterval(() => { console.log('This will run every second!'); }, 1000); return () => clearInterval(interval); }, []); I am intri ...

Updating the background of a button with Vue JS by utilizing an object upon clicking

If you have three buttons and want to change the background color when clicked, for example, clicking on the red button should turn the background color red. However, there is an important detail here: if you click on one button and then another, the old c ...

Console output shows that the function results in undefined

When I pass a string parameter to a function, I expect the console to display "reff", but it is showing "undefined" instead. Here is the code snippet: var _ref; function foo(_ref='reff') { var bar = _ref.bar; return console.log(bar); } foo ...

JS receiving a reference to an undefined variable from Flask

I referenced this helpful post on Stack Overflow to transfer data from Flask to a JS file. Flask: @app.route('/') def home(): content = "Hello" return render_template('index.html', content=content) HTML <head> ...

Close the ionicPopup by tapping anywhere

Currently, I have implemented an ionicPopup that automatically closes after a certain time limit. However, I am wondering if there is a way to configure it to close with a single or double tap anywhere on the screen instead. While I am aware that setting a ...

Tips for simulating mouse events in Jasmine tests for Angular 2 or 4

New to Jasmine testing, I'm exploring how to test a directive that handles mouse events such as mouse down, up, and move. My main query is regarding passing mouse coordinates from the Jasmine spec to my directive in order to simulate the mouse events ...

Reactjs and Isotope offer the ability to expand and collapse on click. In this unique feature, only one item can be expanded at

Currently, I am working on refining an isotope application where each item expands upon clicking it and collapses when another item is clicked. However, the issue I am facing is that multiple cells can be opened simultaneously. I am looking for the most ef ...

"Injecting the value of a jQuery variable into a PHP variable

<script type="text/javascript"> $(document).ready(function(){ $("#t_select").change(function(){ var table_name = $("#t_select").val(); $.ajax({ type: 'POST', ...

A step-by-step guide on setting up an event listener for dynamically generated HTML using JavaScript objects

In my JavaScript code, I am creating object instances that include HTML elements in the form of buttons. These buttons are dynamic and have words generated dynamically as well. I want these buttons to execute certain functions when clicked. The challenge I ...

Use AngularJs service injected in run closure for testing purposes

Testing an angularjs service called MyService has been a bit challenging. It seems like Angular tries to use the service before it is fully loaded when I try to inject it directly. However, if I mock MyService using $provide, it does work but then I don&ap ...

Begin a new countdown timer upon clicking the next button

Currently, I am developing a bid auction website and I have implemented a countdown timer script. The timer works perfectly on the initial window load. However, when I click on the restart button, it fails to reset the countdown timer to a new value. < ...

What is the best method for starting a string using the symbol '~'?

Hello everyone! I have a task that requires me to add a special feature. The user needs to enter something in a field, and if it starts with the tilde (~), all subsequent entries should be enclosed in a frame within the same field or displayed in a list ...

Making a Zoom effect using p5.js

I have searched for a solution to this question multiple times, but none of the answers I came across seem to work for me. Currently, I am able to allow the user to scale an image with a simple scale(factor) call. However, now I am attempting to implement ...

Order of execution for setImmediate() and setTimeout() callbacks compared to I/O callbacks

In the world of Node.js, the event loop powered by libuv is divided into specific phases. The poll phase is where we wait for I/O tasks to complete before running their associated callbacks. The length of this waiting period is determined by timers, timeou ...

Connecting elements within an object using VueJs

Within my object "info_login," I gather account information: async created() { try { const res = await axios.get(inscriptionURL); this.comptes = res.data; this.comptes.forEach(element => { const data = {'pseudo': ...

Problem with escaping special characters in random string HTML

As I was in the process of creating a JavaScript tool to generate random strings, with or without special characters, I stumbled upon an inspiring snippet that caught my attention: (): function randStr(len) { let s = ''; while (len--) s += ...

What is the best practice for importing React components?

In my experience with React, I've noticed two different ways of importing and extending components. The first way that I typically use is shown below. import React from 'react'; class SomeClass extends React.Component { //Some code } ...

Unfulfilled promises are left hanging

I've encountered a problem while writing a unit test for my Angular application using Jasmine with a mock service. The promise I am trying to run is not functioning as expected. Below is the service code: CreateItemController = $controller('Cre ...