Troubleshooting Problem with Angular JS Ng-Repeat

I have a specific situation where I want to showcase the elements that exist in only one array. If an element is also present in another array, there is no need to display it.

My HTML structure looks like this:

<div ng-repeat="array1Value in array1">
    <div ng-repeat="array2Value in array2">
        <div ng-if="isNotFound(array1,array2Value.id)">
            <span>{{array2Value.name}}</span>
        </div>
    </div>
</div>

This is what my JavaScript class entails:

var app = angular.module("MyApp",{});

app.controller("MyController",function($scope) {
    $scope.array1 = [
        {
            id:"1",name:"one"
        },
        {
            id:"2",name:"two"
        },
        {
            id:"3",name:"three"
        }
    ];

    $scope.array2 = [
        {
            id:"1",name:"one"
        },
        {
            id:"2",name:"two"
        },
        {
            id:"4",name:"four"
        }
    ];

    $scope.alreadyPrinted = [{}];

    $scope.isNotFound = function(array,value){
        for(i = 0; i < array.length; i++){
            if (value === array[i].id) {
                return false;
            }
        }

        if($scope.alreadyPrinted.indexOf(value) > -1){
            return false;
        } else {   
            $scope.alreadyPrinted.push(value);
            return true;
        }
    }
});

The desired output should only include "four". However, currently nothing is being displayed. Any assistance in resolving this issue would be greatly appreciated.

Answer №1

To solve the issue, eliminate the external loop and use the following code snippet:

<div ng-repeat="item in items">
    <div ng-if="checkIfNotFound(list1,item.id)">
        <span>{{item.name}}</span>
    </div>
</div>

Answer №2

If I understand correctly, your intention is to have True returned if the value is not present in the initial array.

You can experiment with this implementation for your isNotFound function:

$scope.isNotFound = function(array,value){
    for(i = 0; i < array.length; i++){
        if (value !== array[i].id) {
            return true;
        }
    }
    return false;
}

An alternative approach could be:

$scope.isNotFound = function(array,value){
    angular.forEach(array, function(item){
        if (value !== item.id) {
            return true;
        }
    });
    return false; 
}

It seems unnecessary to iterate both over the first array and the alreadyPrinted section. Simplify your HTML code to:

<div ng-repeat="array2Value in array2">
    <div ng-if="isNotFound(array1,array2Value.id)">
        <span>{{array2Value.name}}</span>
    </div>
</div>

Answer №3

It seems that there may be an issue with the code you have already printed out. The current output is displaying 'four'. To troubleshoot, consider inserting an alert box into your code snippet like below:

for (i = 0; i < array.length; i++) {
    if (value === array[i].id) {
        alert('is not found function called');
        return false;
    }
}

When running this code, you will observe 'four' as the output in your browser but only for one iteration. Reviewing and correcting your existing code with the help of the alert box should assist in identifying and resolving the issue.

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

At times, MomentJS may miscalculate and add an incorrect number of hours

My goal is to add a specific amount of hours to a 24-hour time, but I'm encountering an issue with the time 00:00. The code I've written works correctly for all times except midnight. For example, if I have 01:30 and add 1 hour, it gives me 02:3 ...

Highchart displays results for each individual line without the use of commas

I am interested in creating a chart using Highchart with three lines. The first two lines will display data similar to [4.12, 3.34, 5.45] / [3.45, 5.45, 3.23], while the third line should be displayed without any commas, showing results like [7, 4, 2]. Can ...

The JS slider fails to function properly following the migration of AngularJS from version 1.0.8 to 1.2

Seeking assistance with migrating AngularJS from version 1.0.8 to 1.2 and encountering issues with a JavaScript slider that is no longer functioning post-migration... After upgrading to 1.2, added the angular-route.js library and injected 'ngRoute&ap ...

What's the best way to modify the style property of a button when it's clicked in

I am working with a react element that I need to hide when a button is clicked. The styles for the element are set in the constructor like this: constructor(props) { super(props); this.state = { display: 'block' }; this. ...

Error occurs when using Express.js in combination with linting

https://www.youtube.com/watch?v=Fa4cRMaTDUI I am currently following a tutorial and attempting to replicate everything the author is doing. At 19:00 into the video, he sets up a project using vue.js and express.js. He begins by creating a folder named &apo ...

Issues with Ajax calls not functioning properly within CakePHP

I'm attempting to make an AJAX request in CakePHP. The submit button is marked as #enviar and the action as pages/contato. This is the code for my AJAX request: $(document).ready(function() { $('#enviar').click(function(){ $. ...

Incorporate an HTML form into the primary HTML webpage using AngularJS application technique

As a newcomer to AngularJS, I am attempting to grasp how it can be integrated with an ASP.NET-MVC5 application. For my initial test, I want to launch an AngularJS app from a basic HTML page (in this case index.html) where the app contains a form template i ...

Leveraging Angular's ng-repeat and ng-show allows for specific data extraction from JSON

Looking to showcase the title and description of three items from a carousel, with data sourced from a JSON file via a unique code. Wondering if utilizing ng-show to specify 'if this matches code01 then display the corresponding data for that item&apo ...

modify an element using jquery

Hey there! I'm facing an issue where I have an ID of #item_quantity in a span, and I want it to refresh its contents once a button with the ID of #update_cart is clicked. It seems that everything else updates fine on click, but for some reason, the sp ...

Unable to detect errors using React/Redux

I encountered a login error handling issue with redux that is structured like this: export const login = (params: any) => async (dispatch: Dispatch) => { try { const authData = await API.post("login", params); sessionStorage.setIt ...

Angular index.html file can include a conditional script

I am currently working on an Angular project, where the index.html serves as the main entry point for the application, just like in any other Angular project. This file contains important links and configurations. Within the HTML code snippet below, you w ...

Choosing an ID along with a numerical value in jQuery

Being new to both stackoverflow and jQuery, I'm facing a challenge in creating a basic function. In my website, there are multiple links with IDs such as "filtro1", "filtro2", and so on. My goal is to write a single piece of code that will be trigger ...

Is there a way for me to incorporate the input parameter value passed to a JavaScript function into the popup that is being opened by the function itself?

I am not very proficient in PHP and JavaScript, and I'm facing an issue while trying to pass a value from a main page to a popup page that is defined within this main page. To provide more context: In my account.php page, there is a link like this: ...

Issue with Angular and Karma: HTTP GET request not running

Currently, I am working on an AngularJS project that utilizes Karma to execute some unit tests directly in the browser. To conduct these tests, I have opted for mocha as the test framework. The challenge I am facing lies in running specification tests tha ...

Preserving the video's aspect ratio by limiting the width and height to a maximum of 100%

I am trying to integrate a YouTube video using their embed code in a "pop-up". However, I am facing an issue where the video does not resize to fit within the height of its parent. I want it to be constrained by the div#pop-up that contains the video. Curr ...

Upon reloading, Nextjs static build automatically redirects users to the homepage

After creating a static Next.js build using npm run export, I encountered an issue while deploying the build on S3 or any other web server such as Apache with .htaccess or Nginx. When accessing the routes by pasting them directly into the browser, they wou ...

Click events are unresponsive when used within ng-repeat

Having trouble with ng-click inside of ng-repeat. It seems to work fine outside of it. Check out this JSFiddle link <div ng-controller="MyCtrl"> <a ng-click="triggerTitle='This works!'">test</a> <h5>Please select tri ...

Tips for transferring a calculated value from a child component to a parent component in ReactJs

In my current project, I am faced with the challenge of passing a calculated value from a child component back to its parent. The child component is designed to utilize various user inputs to compute a single value that needs to be returned to the parent. ...

Issue encountered in NestJS/TypeORM: Unable to modify the property metadata of #<Repository> as it only has a getter method

When attempting to launch my nestjstutorial app, I encountered the following error message. The backend is connected to a PostgreSQL database. TypeError: Cannot set property metadata of # which has only a getter at EntityManager.getCustomRepository (D:&b ...

Receiving a blank string after calling fs.readFile within the chokidar.watch(path_file).on('change', ...) function

This is my current Node project setup: https://github.com/tlg-265/chokidar-issue https://i.stack.imgur.com/qYKlR.png $ git clone https://github.com/tlg-265/chokidar-issue $ cd chokidar-issue $ npm i $ npm run watch-changes The project monitors changes ...