What is the best way to delete a specific li element within an ng-repeat loop in Angular

Within my list, there is a specific removePortfolio function attached to one of the divs at the bottom. The purpose of this function is to trigger the ng-hide="tickerRemoved" only for that particular list item and not affect any others.

HTML Gist: https://gist.github.com/leongaban/cf72e5d0229155dd011f
Directive Gist: https://gist.github.com/leongaban/22a8feb9dbeea0b90135

<ul ng-show="loadingTickersDone" class="tickers-list">

    <li class="ticker-li"
        ng-repeat="ticker in tickers"
        ng-hide="tickerRemoved"
        ng-class="{'selected':toggleTicker.item == $index}"
        ng-mouseleave="hideTickerOptions()">

        <div class="ticker"
             ng-click="toggleTicker.item = $index;
                       selectTicker(ticker.ticker);
                       revealTickerOptions()">
             {{ticker.ticker}}
        </div>

        <div class="add-to-portfolio"
             ng-show="tickerOptions"
             ng-mouseleave="hideTickerOptions()">

             <div ng-show="addOption"
                  ng-click="addPortfolio(ticker.ticker)">+ Portfolio</div>
             <div ng-show="removeOption"
                  ng-click="removePortfolio(ticker.ticker)">- Portfolio</div>
        </div>
    </li>

</ul>

The remove function within the directive is as follows:

var vs = $scope;

vs.removePortfolio = function(ticker) {
    this.tickerOptions = false;
    ApiFactory.deleteWatchList(ticker).then(function(data) {
        showMessage(ticker+' removed from portfolio!', data.data.status);
        this.tickerRemoved = true;
    });
};

An error is encountered with the line this.tickerRemoved = true;, possibly due to the scope hierarchy.

Contrastingly, using this in a higher-level function like below works without issues:

vs.revealTickerOptions = function() {
    this.tickerOptions = true;

    if (tickerView === 'all') {
        this.addOption    = true;
        this.removeOption = false;
    }
    else if (tickerView === 'port') {
        this.addOption    = false;
        this.removeOption = true;
    }
};

How can I exclusively remove the <li class="ticker-li" item when triggering the removePortfolio() function?

Answer №1

ng-hide="tickerRemoved" should actually be ng-hide="ticker.tickerRemoved" since tickerRemoved pertains to a specific ticker.

The same goes for ng-show="tickerOptions"... it should be

ng-show="ticker.tickerOptions"</code based on the context.</p>

<p><code>ng-click="removePortfolio(ticker.ticker)">
needs to be changed to
ng-click="removePortfolio(ticker)">
in order to pass the entire ticker object.

To complete this, you will have to modify your remove ticker function. The following code snippet should do the trick:

vs.removePortfolio = function(tickerObject) {
    var ticker = tickerObject.ticker;
    tickerObject.tickerOptions = false;
    ApiFactory.deleteWatchList(ticker).then(function(data) {
        showMessage(ticker+' removed from portfolio!', data.data.status);
        tickerObject.tickerRemoved = true;
    });
};

In general, it seems like you are relying too heavily on the this keyword. It can be quite confusing and I recommend using it sparingly and only when absolutely necessary to avoid confusion in future maintenance of the code.

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

What is the best way to incorporate server-side rendered content from a CMS to hydrate Vue.js?

Consider this scenario: content is managed through a traditional CMS such as Joomla or Drupal content is provided by the CMS as fully rendered HTML and CSS In the Frontend React.js should be utilized for all UI interactions. Despite going over most of R ...

Troubleshooting Bootstrap 4 Modal in JavaScript and Vue: Uncaught ReferenceError: $ is not defined

I'm struggling to figure out how to trigger a Bootstrap 4 modal from my Vue 3 app using JavaScript. Whenever I try to launch the modal, I keep encountering this error message: $ is not defined at eval When looking for solutions, I noticed that most a ...

Dealing with a frustrating roadblock in Three.js where you encounter an "Unknown format" error while trying to work with

Greetings, I am relatively new to THREE.js and currently experimenting with loading a .FBX Object using the FBXLoader found in three/examples/jsm/loaders/FBXLoader while integrating this into React.js. Upon launching the page, I encountered an issue where ...

Using Axios and Typescript to filter an array object and return only the specified properties

I'm currently working on creating an API to retrieve the ERC20 tokens from my balance. To accomplish this, I am utilizing nextjs and axios with TypeScript. However, I'm encountering an issue where the response from my endpoint is returning exces ...

Tips for utilizing the onclick method to modify an ejs variable

, I am currently in the process of developing a web application utilizing Node, Express, and ejs. Specifically, I have created a page that features a series of buttons (displayed in the first table) alongside an associated set of hidden divs (shown in the ...

Using V-For with data fetched from an axios request: A step-by-step guide

How can I dynamically populate V-Cards after making an Axios request to retrieve data? The Axios request is successful, but the v-for loop does not populate with V-Cards. I've also attempted to make the request before the rendering is completed (usin ...

Avoiding Browser Escaping Characters in AngularJS

I have encountered an issue with a directive I created that is designed to highlight code. It seems that browsers are altering the code before it can be properly highlighted. Here is a breakdown of what is occurring: The directive, named my-compile, func ...

Is there a way to dynamically enable ui-sref through element.append in Angular?

I am in the process of developing a pagination directive. Once the total_for_pagination data is filled, the appropriate HTML for the pagination gets generated. Here's my current HTML structure with a maximum of 50 per page: <pagination data-numbe ...

What could be causing my server to not fully read my json file?

I created a function that sends a get request for fav.json and assigned the id="fav_button" button to execute this function. Additionally, I configured an express server. However, upon clicking the button, only the last item in the json file is displayed. ...

Can you explain the distinction between using "require" to return a module and accessing the actual object in node.js?

When working with node.js, the commonly used method to include modules from other files is by using "require", whether it's from our own code or third-party libraries. But for me, there seems to be some confusion regarding the distinction between the ...

Boost All Elements of Object Array Simultaneously with Mongoose Increment Method

I'm currently working on a project to track statistics on users (for a discord bot) like command usage and more. My goal is to store all this data in my mongodb. Essentially, I am aiming to regularly update the database with an array that records use ...

Issue arising in Angular 7 due to the binding between the TypeScript (ts) file and HTML file for the property [min]

I am currently utilizing Angular Cli version 7.3.9 In my project, I have implemented a date type input that is intended to display, in its datepicker, starting from the next day after the current date. This is how I approached it in my .ts file: debugger ...

select attribute not saving on change

My select input has the multiple attribute being set using jQuery. Interestingly, after confirming through console.log that the code functions correctly, the multiple attribute seems to disappear when I check again. Any ideas on why this is happening? The ...

Transform HTML entities to an escaped string in CSS content dynamically

I am aware that special html-entities like &nbsp; or &#246; or &#x0F0; cannot be incorporated within a css block like the following: div.test:before { content:"text with html-entities like `&nbsp;` or `&#246;` or `&#x0F0;`"; } ...

The valueChanges event of a Reactive Form is activated whenever options from a datalist are selected

Whenever a user types into the input field, I am making an API call to retrieve and display data in a datalist for autocompletion (typeahead). control.get('city').valueChanges.pipe( map((searchText) => searchText.trim().toLowerCase()), fi ...

What is preventing me from assigning to a class variable within a $http success handler?

During the course of my project, I have encountered a perplexing situation that is difficult to comprehend. My intuition tells me that the issue lies in a peculiar nuance of javascript while I am working in TypeScript. Unfortunately, I am unable to prove t ...

After a page reload, Material-UI stops functioning properly

I am currently working with Material UI in a Next.js project. When I run npm run dev, everything looks good. However, whenever I refresh the page, all the styling breaks. Has anyone experienced this issue before? It seems like Material-UI is no longer func ...

Patience is key for a fully completed JSON in JavaScript

I recently came across a similar discussion on Stack Overflow, but it involved using JQuery which I'm not using. My issue is that I need to ensure my JSON data is fully loaded before calling my function. I understand the concept of using a callback, ...

'jQuery' is not recognized as defined, error no-undef

I am currently working on a file that utilizes jQuery for testing purposes: (function($) { "use strict"; // Start of use strict // Configure tooltips for collapsed side navigation $('.navbar-sidenav [data-toggle="tooltip"]').tooltip({ ...

Display jqgrid with borders and insert extra headers text at the top of the grid

function generateTableWithText(){ $("#active_grid").jqGrid("exportToHtml",{ includeLabels : true, includeGroupHeader : true, includeFooter: true, autoPrint : true ...