Removing Angular scope upon splice operation

Why does my entire list get destroyed when trying to remove an item using splice in JavaScript?

HTML:

<ul class="nav nav-tabs">
  <li ng-repeat="pane in panes" ng-class="{active:pane.selected}">
      <a href="" ng-click="select(pane)">
          {{pane.title}}&nbsp;
          <sup ng-click="close(pane)">x</sup>
      </a>
  </li>
  <li>
      <a href="" ng-click="createPane()">+</a>
  </li>
</ul>

JS

.controller('editCtrl', ['$scope', function($scope){

    $scope.panes = [];
    var ctrl  = this;

    $scope.select = function(pane) {
      angular.forEach($scope.panes, function(pane) {
        pane.selected = false;
      });
      pane.selected = true;
    };

    this.addPane = function(pane) {
      if ($scope.panes.length === 0) {
        $scope.select(pane);
      }
      $scope.panes.push(pane);
    };
  
    $scope.createPane = function() {
        var pane = {
            title: 'untitled',
            content: 'Scope:'+$scope.$id
        }
        ctrl.addPane(pane);
    };

    $scope.close = function(pane) {
        var idx = $scope.panes.indexOf(pane);
        
        if (idx != -1) $scope.panes.splice(idx, 1); 
    }

}]);

I am specifically focused on the close method and looking for a solution.

Answer №1

It seems that your list remains intact.

However, the presence of href="" in those <a> tags causes the entire page to refresh when clicking the x icon.

To prevent this, try eliminating the href attribute like so:

<ul class="nav nav-tabs">
  <li ng-repeat="pane in panes" ng-class="{active:pane.selected}">
      <a ng-click="select(pane)">
          {{pane.title}}&nbsp;
          <sup ng-click="close(pane)">x</sup>
      </a>
  </li>
  <li>
      <a ng-click="createPane()">+</a>
  </li>
</ul>

I hope this solution proves helpful.

Answer №2

When you pass the index of the pane to be removed using $index as the parameter for your close($index) function, you're already indicating which pane should be closed.

Therefore, your close function should be structured like this:

$scope.close = function(i){
    var removedPane = $scope.panes.splice(i,1);
    // Here you can perform additional actions with the "removedPane" if needed
};

This particular line

var idx = $scope.panes.indexOf(pane);

attempts to locate the index of the position being passed to the function, resulting in idx likely being undefined.

EDIT

To correctly call the close function, use the following syntax:

`ng-click="close($index)"`

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

How can I refresh the information without appending it to the existing table using JavaScript and jQuery?

I am currently utilizing the pusher API and I am facing an issue where the data gets added to my table every time a new state is called. Instead, I want to update the existing data in the table without creating a new row every time. I only want to add a ne ...

Testing the revised react component through unit testing with jest and enzyme

I am currently working on writing the test file for this code snippet. Here is my approach: import React from 'react'; import renderer from 'react-test-renderer'; // import { mount } from 'enzyme'; import LazyToastMessage from ...

Delete a specific element within an Angular component by utilizing Angular or Jquery through an ng-click event handler

I am having trouble deleting an image element on my page using Angular and jQuery. I attempted to remove the image using $(this).remove() in my controller function, but it doesn't seem to work. Can anyone provide any suggestions or solutions? View & ...

Calculating the combined cost of items in the shopping cart

I encountered a small problem while working on my project. I'm trying to calculate the total price of all items in the cart by summing them up, but my mind is drawing a blank at the moment. Below is the code snippet I am currently using: const { ca ...

The functionality of Angular binding appears to be experiencing issues when used in conjunction with ngIn

On my timeline, I have posts displayed using a $firebaseArray that updates properly when there are changes. However, I noticed that when I try to bind other data, it only works when ngInfiniteScroll is fetching more data from Firebase, triggered by scrolli ...

Having trouble generating an image with JavaScript

I am currently working on incorporating an image onto a webpage using JavaScript. Surprisingly, even the alert('This function works!') is not displaying anything! What could be causing this issue? Please assist! <!DOCTYPE html> <html> ...

Having difficulty invoking JavaScript code from PHP

When a button is clicked, this Javascript function is triggered: var xmlhttp; function register() { xmlhttp=GetXmlHttpObject(); alert("pass"); if(xmlhttp==null) { alert("Your browser does not support AJAX!"); return; ...

Expand the capabilities of a jQuery plugin by incorporating new functions or modifying existing ones

I have a task to enhance the functionality of a jQuery Plugin (https://github.com/idiot/unslider) by adding another public method. (function(){ // Store a reference to the original remove method. var originalMethod = $.fn.unslider; // Define a ...

Vue alert - Cannot access indexOf property of a value that is undefined

After browsing through numerous similar issues on StackOverflow, none seem to address the specific problem I encountered... I have been smoothly working on a Vue JS project + Laravel until I suddenly encountered an error that seems unsolvable (even though ...

What is the best way to activate tooltip visibility on a mobile device?

I have implemented the {onmouseover} variable with the <a> tag to trigger the script function on hover. Here is an example: <a class="tooltip" href="#" onmouseover="tooltip.pop(this, '#tip3', {sticky:true, posit ...

Tips for creating a mirrored image on an IcosahedronGeometry using three.js

My goal is to create a rotating IcosahedronGeometry in three.js and have it reflect an image on the front side of the geometry. After successfully creating the IcosahedronGeometry and implementing rotation on its axis, I encountered an issue when trying t ...

What is an effective method for coordinating JQuery animations simultaneously?

My current understanding of $("#someElement").animate() is that it will run asynchronously in relation to other JavaScript statements. For example: $("#anotherElement").css("display", "none"); $("#someElement").animate(); //The CSS display may change a ...

Issue with Access Denied Error in Internet Explorer 11 when Using AngularJS

Every software development process consists of two essential components. FIRST, the hard work of developing the application. SECOND, the even harder task of making it compatible with the notorious Internet Explorer. Currently, we have an AngularJS (v1.3.1 ...

Preserve present condition following a jQuery click event

I'm facing a challenge where I need to hide a button upon clicking another button, but the problem is that when the page refreshes, the hidden button becomes visible again. My objective is to keep it hidden even after refreshing the page and only reve ...

Issue with Bootstrap4 Carousel not scrolling horizontally

I'm currently working on creating a carousel following the Bootstrap code snippet page. It features three images and is designed to have slide controls that move left and right. The script tags with the necessary scripts are located at the bottom of t ...

Searching for specific values within a date range in MongoDB, focusing on particular times of the day

I am working with a basic mongodb database that includes two key fields: date and value In my node project using mongoose, I have the following code to retrieve readings within a specific date range: Reading.find({ date: { $gte: startDate, $lt ...

Tips for configuring Visual Studio Code to utilize path mappings for handling automatic imports

In order to streamline my project and avoid messy paths, I am implementing absolute paths that will allow for consistent imports regardless of the file's location in the project tree. For this purpose, I made adjustments to the tsconfig.json: "paths ...

JavaScript file slicing leads to generating an empty blob

I am currently working on a web-based chunked file uploader. The file is opened using the <input type="file" id="fileSelector" /> element, and the following simplified code snippet is used: $('#fileSelector').on('change', functio ...

Validating whether another element is checked when a radio button is unchecked

I'm completely stuck on this issue - I just can't figure out how to dynamically change the image when a user unchecks a radio button (i.e., checks a different radio button). Here is the code: handleCheckbox = e => { let target = e.targe ...

iOS 10.3.1 causing Ionic 2 (click) event to trigger twice

I am currently working on an Ionic 2 app and I am facing an issue with the click event. When I test the app on a device and click on a button, let's say to trigger an alert, the function executes once. However, if I click on the button again, the fun ...