Issue: The find() function in JavaScript is not functioning as expected when used alongside AngularJS version 1

Hey there, I'm currently exploring AngularJS and facing some challenges with it. I'm attempting to retrieve an item from the madeUpCards[] array using the find() function in JavaScript.

<body ng-app="myApp" ng-controller="myCtrl">

<h3>{{getCardById('14')}}</h3>
</body>

Here is the array:

    $scope.madeUpCards = [
     {
        "id": "23",
        "name": "The brain",
        "closed": true,
    },
     {
        "id": "2",
        "name": "Portal dead",
        "closed": true,
    },
     {
        "id": "14",
        "name": "Holiday",
        "closed": true,
    },
     {
        "id": "13",
        "name": "warded",
        "closed": true,
    },
];

JavaScript code:

const app = /**
* myApp Module
*
* Description
*/angular.module('myApp', []).controller('myCtrl', ['$scope', function($scope){

    $scope.getCardById = function(id) {
        this.id = id
        let foundCard = $scope.madeUpCards.find(function(card, index){
            return card.id == this.id
        });
    return foundCard.name;
    }

}]);

The console shows:

 angular.js:15536 TypeError: Cannot read property 'find' of undefined
  at ChildScope.$scope.getCardById ((index):49)
  at fn (eval at compile (angular.js:16387), <anonymous>:4:234)
  at expressionInputWatch (angular.js:17398)
  at Scope.$digest (angular.js:19095)
  at Scope.$apply (angular.js:19463)
  at bootstrapApply (angular.js:1945)
  at Object.invoke (angular.js:5122)
  at doBootstrap (angular.js:1943)
  at bootstrap (angular.js:1963)
  at angularInit (angular.js:1848)

I need help fixing this issue or figuring out what went wrong. Any guidance would be appreciated!

Answer №1

To make the necessary changes in your controller, replace const madeUpCards with $scope.Cards. Instead of passing in Cards, simply use

<h3>{{ getCardById('14') }}</h3>

In your controller, update to:

$scope.Cards = [
     {
        "id": "23",
        "name": "The brain",
        "closed": true,
    },
     {
        "id": "2",
        "name": "Portal dead",
        "closed": true,
    },
     {
        "id": "14",
        "name": "Holiday",
        "closed": true,
    },
     {
        "id": "13",
        "name": "warded",
        "closed": true,
    },
];

...

$scope.getCardById = function(id) {
    let foundCard = $scope.Cards.find(function(card, index){
        return card.id == this.id
    });
    return foundCard.name;
}

In the HTML:

<body ng-app="myApp" ng-controller="myCtrl">

<h3>{{ getCardById('14') }}</h3>
</body>

You can still pass in Cards to getCardById, but it's redundant since it's accessible within your controller.


When using AngularJS, elements need to be defined on the scope for DOM binding.

The variable Cards was created as a local variable in the controller, not part of the scope. Therefore, when you pass Cards into a function in the HTML, it's undefined (not part of the scope).

This results in passing undefined into your controller and trying to call find on undefined, leading to an error.

Answer №2

Uncertain about the status of Cards, consider looking into it

<h3>{{ findCard([
     {
        "id": "23",
        "name": "The brain",
        "closed": true,
    },
     {
        "id": "2",
        "name": "Portal dead",
        "closed": true,
    },
     {
        "id": "14",
        "name": "Holiday",
        "closed": true,
    },
     {
        "id": "13",
        "name": "warded",
        "closed": true,
    },
], '14') }}</h3>

Answer №3

<h3>{{ retrieveCardById(Cards, '14') }}</h3>

Based on this code snippet, it is expected that the variable Cards will be linked to $scope.

To accomplish this, make sure to initialize $scope.Cards at the beginning of the controller like so:

const app = /**
* myApp Module
*
* Description
*/
angular.module('myApp', []).controller('myCtrl', ['$scope', function($scope){

    $scope.Cards = [
        {
            "id": "23",
            "name": "The brain",
            "closed": true,
        },
        {
            "id": "2",
            "name": "Portal dead",
            "closed": true,
        },
        {
            "id": "14",
            "name": "Holiday",
            "closed": true,
        },
        {
            "id": "13",
            "name": "warded",
            "closed": true,
        },
    ];

    $scope.retrieveCardById = function(cards, id) {
        this.cards = cards
        this.id = id
        let foundCard = this.cards.find(function(card, index){
            return card.id == this.id
        });
        return foundCard;
    };

}]);

Have fun with your development activities.

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

Ways to execute a function inside a div or custom tag attribute

Looking for guidance on calling a function within a custom tag: <t-dropdown name='Name' callback="testFn"> </t-dropdown> <script> function testFn(value){ console.log(value); } </script> In JavaS ...

Error: The function 'enter' cannot be called on the data selection from the SVG append and attribute select statement in the code

I am attempting to replicate the force-directed graph showcased by Bostock in this example https://bl.ocks.org/mbostock/4062045 using my own dataset. By leveraging Django serializers to parse the JSON-formatted data, I have successfully retrieved the requ ...

The RSS feed is stretching beyond the limits of the table's height

Seeking assistance to adjust the height of an RSS feed widget on my website. The widget is from RSS Dog and I do not have access to the style.css file as it is hosted externally. Despite trying to modify the JavaScript code provided by RSS Dog to set the h ...

Understanding the difference between the local and global locations of a three.js Object3D

Initially, I envisioned my small 'ship' with turrets that could track a target. This is the jfiddle I created to showcase it. You can view it here. However, when the turrets track, they behave strangely. I noticed that the turret seems to believe ...

Exploring the indexOf method in Jade

Currently using Jade and Express. '#{value.users}' is an array data type. '#{user.username}' is a string data type. Attempting to utilize the if '#{value.users}'.includes('#{user.username}') method. When true, I ...

Can you send an array of objects as data in an AJAX post request?

My primary objective is to gather the dropdown values from a webpage and then send them to a PHP file for processing. Currently, I am using jQuery to achieve this by creating an overall schedule array and adding each element to it for updating. Here' ...

Error 19: Constraint violation - duplicate entry detected

While trying to set up my app, create a local database, and insert the very first user who has logged in locally, I encountered an error message at a specific point in the code. Here's where it happened: angular.module("greenApp") .service("d ...

The shop is unable to find a proper reducer while utilizing redux-toolkit

I'm experiencing an issue with the configureStore function in redux-toolkit. Whenever I attempt to call dispatch on a page, I'm getting the error 'Store does not have a valid reducer'. I've double-checked my imports and ensured tha ...

Tips for effectively utilizing v-model and v-select in a dynamic manner

Is it possible to have a group of select elements in Vue.js that work independently with v-model without needing separate data properties for each one? For example, select 1 and select 2 should be treated as one group, while select 3 and select 4 are anot ...

Specify touch event regions with the ngTouch directive

I recently implemented ngTouch in my AngularJs web app to detect swipe left and right gestures. I am using this feature to open and close a side bar menu. Currently, the swipe events are linked to the entire wrapper like this <div ng-style="body_st ...

Tips on avoiding a page reload following a form submission using JQuery

Currently developing a website for my app development project, I've encountered an unusual issue. Utilizing some JQuery to transfer form data to a php page called 'process.php' and then add it to my database. The strange part is that the pa ...

What is the method for including a JavaScript file at the bottom of the </body> element in GatsbyJS?

I'm a newcomer to React and Gatsby and I'm looking for assistance on how to add JS at the bottom of a GatsbyJS site. I'm having trouble finding where to place the script since there is no index.html file with </body> in my /src folder. ...

JavaScript: Creating an array to store the most recent 5 search queries

I am creating a React-Redux application with a search feature based on city names. https://i.sstatic.net/eFGVz.gif Below the input field, I want to display the last 5 cities that have been searched for. To achieve this, I am storing all entered cities i ...

The jQuery Multiselect filter contradicts the functionality of single select feature

http://jsfiddle.net/rH2K6/ <-- The Single Select feature is functioning correctly in this example. $("select").multiselect({ multiple: false, click: function(event, ui){ } http://jsfiddle.net/d3CLM/ <-- The Single Select breaks down in this sc ...

Discovering the URL of an AJAX request on any given website

Is there a way to retrieve the URLs of AJAX requests that are sent by the current page on a website using a browser or another tool? ...

Is it possible to create a function that executes if a checkbox is checked, and another function if

When the radio button with the ID m1 is checked, my mesh updates its position. I attempted to make the mesh return to its original position if "#m1" is no longer checked. Is it necessary to trigger a function when checked and a different function when no ...

Is there a way to dynamically inject a stylesheet in NextJS?

I'm facing a challenge in my nextJS application where I need to dynamically load a stylesheet based on the user preference fetched from the database. To achieve this, I have added the stylesheet link in the Head component (next/head) like so: <Hea ...

Locate a specific tag within an XML document using user input and then showcase the content that is encapsulated by it utilizing Node

Could someone kindly advise on how to locate a tag name within an XML dom based on user input and then iterate through and display all content within it? For example, if the user enters 'unit', the program should display everything within the uni ...

Organizing string enum in Typescript and AngularJS - Tips and Tricks

In my Typescript file, I have defined an enum called PriorityLevel: enum PriorityLevel { High = <any>'High', Normal = <any>'Normal', Low = <any>'Low'} In the HTML section, I have the following code: <b ...

What is the best way to search for a CSS selector that includes an attribute beginning with the symbol '@'?

Whenever I want to target an element with a click event, I usually use the following jQuery selector: $('div[@click="login()"]') <div @click="login()"> Login </div> However, when I tried this approach, it resulted ...