Using the same function in two different locations will only work for one instance

I have an AngularJS application where I am using a function called foo(bar) that takes bar as a parameter. The data for bar is retrieved from a web API, and I loop through this data using ng-repeat which works perfectly fine.

<li class="list-group-item" ng-repeat = "tag in subreddit.tags">
        <a href="javascript:void(0);" ng-click="subreddit.getData(tag)" target="_blank">{{tag.data.url}}</a>

      </li>

The getData function works as expected with the ng-repeat directive. However, I encountered an issue when defining another instance of getData in the same app:

    <button class="btn btn-success btn-block" ng-click="subreddit.getData(tag);">Load Feeds...</button>

This time, getData does not work because the parameter 'tag' is undefined, unlike in the case of ng-repeat where it was provided by the data.

To further illustrate my problem, I have created a demo to showcase the issue.

Steps to reproduce:

1. Click on the Reddit links to see the data being populated correctly in the console

2. Click on the red button "Load Feeds" which calls the same function but doesn't work

If anyone can provide insight into how to resolve this issue or point out what mistake I might be making, I would greatly appreciate it.

Demo of the Issue:

http://jsbin.com/xexawumojo/edit?html,js,output

Answer №1

Instead of defining a new instance, you continue to utilize the existing controller. However, since you have already written without a valid data object, the tag is now unknown because you are no longer within the repeat loop.

To remedy this issue, consider implementing a mouse click handler that can save the selected tag in the controller and then utilize this saved tag for subsequent actions.

Answer №2

I'm a bit confused by the question, but it seems like there might be a misunderstanding of the concept. Here is a program that may provide some help:

<!DOCTYPE html>
<html ng-app="MyApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
  <div class="first" ng-controller="SubRedditController as subreddit">

   <ul class="list-group">
    <!-- If you declare the tag variable here, its scope will only be within the following li element -->
      <li class="list-group-item" ng-repeat = "tag in subreddit.tags">
        <a href="javascript:void(0);" ng-click="subreddit.getTagAssociatedData(tag)" target="_blank">{{tag.data.url}}</a>

      </li>
    
     <ul>
        <li class="list-group-item" ng-if="subreddit.full_description">
        {{subreddit.full_description.description}}
      </li>
     </ul>
  </div>

</body>
</html>

It appears that the value being passed is undefined, so the function may execute like this:

vm.getTagAssociatedData = function(data) { 
// When data is undefined         
var full_description = data.data; // full_description = undefiend
vm.full_description = full_description; // vm.full_description = undefined  
          console.log(data); // no output
        }

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

Safari 15.6.1 does not support background video playback in Next.js

Currently using Safari version 15.6.1 for a small website project, I have encountered an issue where the video appears frozen with an arrow in the middle. Oddly enough, this problem only occurs on Safari as both Chrome and Firefox display the code correctl ...

Present the array elements in a format that allows the user to easily choose an option and explore the content

I'm currently working on a project where users will take a Computer Based Test and be graded on a selected subject. I have a database set up with questions and multiple choice options. My goal is to display the questions in a way that allows users to ...

Guide on integrating react-tether with react-dom createPortal for custom styling of tethered components based on their target components

Within a Component, I am rendering buttons each with its own tooltip. The challenge is to make the tooltip appear upon hovering over the button since the tooltip may contain more than just text and cannot be solely created with CSS. The solution involves ...

Add HTML content to an element within a directive and create a custom function to manipulate it locally

In my AngularJS application, I am faced with a variety of complex inputs scattered throughout. Some inputs utilize directives for autocompletion functionality, like those powered by Google Places or Twitter Bootstrap. I am currently exploring the concept ...

Stopping React from re-rendering a component when only a specific part of the state changes

Is there a way to prevent unnecessary re-renders in React when only part of the state changes? The issue I'm facing is that whenever I hover over a marker, a popup opens or closes, causing all markers to re-render even though 'myState' rema ...

Express & React: Be cautious of client checksum and style while server-side rendering

Recently delving into the world of React server side rendering, I'm currently working on a small demo utilizing technologies such as React, Redux, React Router, and Material UI. The main issue I'm encountering is the following warning. I am uncer ...

Error: An unidentified SyntaxError occurred with an unexpected token < within an anonymous function displayed on the console

In the process of developing an upload file application. The implementation involves AJAX and PHP. Everything functions smoothly on the localhost, but upon transferring it to the web server, a specific error is encountered: Uncaught SyntaxError: Unexpe ...

Connect to a node.js server from a different network

Looking to set up a basic live chat using node.js, socket.io, and express. Managed to get it working on my local network, but wondering if there's a way for someone from another internet connection to connect without me needing to pay for server space ...

The reason why React.js does not automatically bind its functions to the "this" object

I cannot understand the purpose of a function not being bound by this object. In my opinion, all functions should be bound by 'this'. So why doesn't Reactjs automatically set bind(this) by default? For instance, in the code below, if I didn& ...

Complete the dynamic form submission in a non-blocking manner

My goal is to dynamically add text fields with the click of a button I also aim to extract data from these text fields and insert it into the database Currently, all functions work smoothly, I just need this additional feature. Per ...

Passing variables with AngularJS and Typescript using a service

Currently in the process of developing an application using AngularJS, I am faced with the challenge of passing a URL when clicking on a menu button in order to utilize that URL within an iframe on another view controlled by a separate controller. Despite ...

When using AngularJS with DateRangePicker, I am encountering an issue where my ng-model does not capture the input text value when I select a date

Trying to establish the selected date range in an ng-model called dateRange in the following HTML. The input text field displays the selected value correctly, but dateRange remains null. What steps can I take to address this issue? <!DOCTYPE html> ...

Auto-complete feature not populating the input field in Google Chrome

Within my register form, I have various INPUT tags present. One of these INPUTs has the name email. <input type=text name=email id=email> When filling out this form in Chrome, I encounter a peculiar behavior. Upon clicking on the email input field ...

Uploading an image using ajax with multer

When using Multer to upload an image file to my Node server, I keep getting 'undefined' when trying to use ajax to send the image. Ajax : image = $("#input-file-img").val() const data = new FormData(); data.appe ...

problem decoding json data from external server

I have a custom Grease Monkey script that is responsible for collecting data from a game and sending it to my server for tracking our team's progress. This process involves multiple Ajax requests between the GM script and the game, followed by sending ...

Retrieving PHP data, utilizing the split method to break apart the commas within the string, and then displaying the information within a div using AJAX for a continuous refresh cycle every 3 seconds

I am attempting to extract data from a PHP string like '10,58,72,15,4,723,' and split it by commas into arrays using the split() method. My goal is to then place these arrays into different div elements and update the data every 3 seconds. Below ...

Tips on storing form data in AngularJS with the Fat Free framework

I am encountering an issue while trying to save data in SQL using Fat Free Framework. I have implemented the front end in AngularJS and I am sending data through an Angular ng-submit button. The AJAX POST request is being made but the data is not getting ...

How can 'this' be converted from D3 JavaScript to TypeScript?

In JavaScript, 'this' has a different meaning compared to TypeScript, as explained in this informative article 'this' in TypeScript. The JavaScript code below is used to create a thicker stroke on the selected node and give smaller stro ...

Is it possible that when a user is redirected to a different URL, Chrome terminates any pending Ajax requests?

Currently, I have a function that allows the user to unlock a list they are currently editing: function cancelLock(id) { $.ajax({ type: "POST", url: "/ajax.php?action=cancelLock", dataType: 'json', data: "id="+ id }); retur ...

I'm encountering an issue with my React 18 application using TypeScript: the module './App' cannot be found

Encountering an issue while attempting to update to react 18. I'm curious if this problem is related to my file types. I am using Typescript, so do both the app and index files need to have a .tsx extension? Both the app and index files are located ...