Extract item from the collection

I am struggling with the following code:

app.controller('modalController', function($scope, $http,$modalInstance, $rootScope, items){

   // Retrieving information
   $http.post('/ajax/bundle', {'items':items}).success(function(data){
       $scope.info = data['info'];
   });

   // [BUTTON] Add Bundle
   $scope.selectBundle = function() {

        // Adding info to the cart
        $rootScope.cart.push($scope.info);
        // Simplified info
        $rootScope.selectedBundle.push(items)
        // Closing the modal
        $modalInstance.close();
   }

   // [BUTTON] Remove bundle
   $scope.removeBundle = function() {
        // Iterating through all selected bundles
        angular.forEach($rootScope.selectedBundle,function(value, key){
           // Checking if exists
           if (angular.equals(value,items)) {
               // Removing from simplified info
               $rootScope.selectedBundle.splice($rootScope.selectedBundle.indexOf(value), 1);
               // removing from cart
               // $rootScope.cart.splice($rootScope.cart.indexOf($scope.info), 1);
           }
       });

       // Closing the modal
       $modalInstance.close();
   }
});

After using:

console.log($rootScope.cart);
console.log($scope.dados);
console.log($rootScope.cart.indexOf($scope.dados));

the console logs the correct position within $scope.selectBundle.

However, when used in $scope.removeBundle, it always returns -1 indicating that it's not found. Can anyone provide some guidance or help me troubleshoot this issue?

Answer №1

Why not just empty the array instead of searching for index?

// [BUTTON] Remove bundle
$scope.removeBundle = function() {
     $rootScope.selectedBundle = [];
     $modalInstance.close();
}

Another approach: Using angular.forEach to iterate through the array and splice elements out.

$scope.removeBundle = function() {
    angular.forEach($rootScope.selectedBundle,function(value, index){
        $rootScope.selectedBundle.splice(index, 1);
    });

   $modalInstance.close();

}

Answer №2

It's possible that there is an issue with your equality function. Have you considered creating a jsFiddle or Plunker to troubleshoot? In the meantime, you can try passing the item you want removed into the calling function like this:

// [BUTTON] Delete package
$scope.deletePackage = function(itemToDelete) {
    console.log(itemToDelete); // pass item to delete
    angular.forEach($rootScope.selectedBundle, function(value, key){
       // Check if item exists
       if (value === itemToDelete) {
           $rootScope.selectedBundle.splice($rootScope.selectedBundle.indexOf(value), 1);
       }
    });

    // Close modal
    $modalInstance.close();
}

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 ng-Options feature does not update the connected label when the drop-down selection is changed

Based on the initial code example by Scott Allen (basic) reference, the ng-model is not updating properly after a selection is made in the drop-down menu. {{engineer.currentActivity}} Current browser: Firefox 50.1.0 Using Angular version: 1.5.9 jQuer ...

Maximizing Efficiency with React.js Search Bar API

As someone who is very new to JavaScript and the realm of React, I have been diving into hooks. However, when attempting to fetch an API for a search bar feature, things didn't quite go as planned. My goal is to retrieve data from a URL (which happen ...

Tips for running multiple .js test files simultaneously with npm (pact files)

My background is in Java and Maven, where I am accustomed to running multiple test files together and sequentially using a command like: mvn '-Dtest=com.my.directory.tests.*Test' test In this setup, all my test files are named to end with the w ...

Calculate the total cost for each row in a table by multiplying the quantity and price using jQuery, then display the result

I'm encountering an issue with my table row calculations involving price and quantity. The calculation results show up correctly in the console, but when I try to display them back on the table, the total sum of the first row gets duplicated into all ...

Revamping a design using Mustache js

I've successfully implemented mustache js to render a template using data from an API, but now I face a challenge in updating the same template at a later time. Within my template, there is a list structured like this: template.html <div id="temp ...

Why doesn't express.js throw an error when the variable 'app' is used within its own definition?

When working with express.js, I find it puzzling that createApplication() does not throw an error. This is because it uses app.handle(...) within an anonymous function that defines the same variable 'app'. I attempted to replicate this in jsFidd ...

Guide to dynamically updating objects-array by adding new elements with an event listener and displaying the changes on an HTML page

My attempt to create a todo application hit a snag when I tried to add a new todo using a form and an event listener. Despite finishing the code, the app only stores the written text in the object-array without actually adding it to the todos list on the H ...

Tips for accessing JSON values in JavaScript

How can I extract values from a JSON object in JavaScript? Below is the code snippet I've tried: var obj={"0.5":0.009333, "0.21":0.048667,"0.31":0.070667}; var value =0.21; var p=0; for(i=0; i<= obj.length ;i++){ if(value== obj[i]) ...

How to retrieve the chosen option from a drop-down menu in WebDriver using JavaScript without relying on the Select Class

Currently, I am in the process of utilizing Webdriver with Java. My goal is to retrieve the selected value from a combobox without relying on the Select class provided by Webdriver. The specific markup that I am dealing with is as follows: <select nam ...

Hover over elements to reveal D3.js tool tips

Currently, I am utilizing a tutorial for graph tooltips and finding it to be very effective: http://bl.ocks.org/d3noob/c37cb8e630aaef7df30d It is working seamlessly for me! However, I have encountered a slight problem... In the tutorial, the graph disp ...

Meteor is not recognizing the defaultValue property in React

I'm puzzled by this issue—it's frustrating that it's not working as expected. <input type="text" id="first_name" name="first_name" className="form-control" defaultValue={this.props.user.first_name} required/> However, I've di ...

Implementing a controller's method within a jQuery/ajax URL in Rails: A step-by-step guide

My goal is to use jQuery/Ajax to create and save data in the cart model by calling the controller's method in the Ajax URL. Here's the jQuery/Ajax script: $(document).ready(function() { $('.add-cart-product').click(function() { va ...

Encountering a problem with the routing/asset pipeline that is causing an undefined

After taking a break from Rails for a while, I recently decided to dive back in. However, I seem to be missing something simple here. It could be due to my limited understanding of how javascript functions within Rails. I believe my haml view is properly ...

I am encountering an issue with identifying a directory in Node.js

This is my HTML code <div id="done_work_1" class="logo-slide-track"> </div> <script>$.ajax({ url: "/static/home/done/", success: function (data) { $(data).find("a").attr("href&q ...

Experiencing an overwhelming number of re-renders due to a specialized React Hook

I have been fetching data from a Neo4J database using the use-neo4j library and developed a custom hook for this purpose. The hook executes a query to retrieve the data from the database and then formats it in a way that enables me to visualize the data ef ...

utilize the functionality of chartjs to overlay images on top of pie chart segments

Currently working with chartjs version 3.6.0 and vue version 2.6.11. My goal is to create charts using chartjs in combination with vue, which has been going smoothly overall. However, I have encountered a challenge that I am struggling to solve. Specifical ...

Image Slider's Functionality Hindered by AJAX

I have been working on implementing a menu bar on a website using an image library called Jcoverflip, where you can find a demo. The Image Slider works perfectly, however, things take a turn when I attempt to load content from different HTML files using AJ ...

Setting up a node application on Heroku by organizing the client and server components into distinct directories

I've spent hours researching, but I still can't fully grasp this concept. My app is set up with the client built using Vue-cli running on port 8080 from a folder called client, and the server runs on port 8081 from a separate folder named server ...

Utilize AJAX to dynamically refresh the page without having to reload it, enabling the use of both POST and GET methods

In order to avoid reloading the page when refreshing, I am utilizing Ajax for this particular 3-sided content along with JavaScript. Here is the code: Content: <ul id="nav"> <li><a href="ajax_adat.php?id=8&epul=0">Data</a>< ...

Storing JSON data in a SQL database

Storing JSON in an MsSql database and passing it to Javascript via a PHP script has been working perfectly. However, when trying to include extra text that is not part of the formatting string, like d, h, a, or p characters, encountered some challenges. Lu ...