reinitializing an array duplicate within an angular function following the use of .splice()

My goal is to create a dropdown menu in Angular that automatically removes the current page from the list when navigating to another view. I want the menu to reset and remove the now-current view every time a new view is loaded.

This is the array of objects that forms the dropdown menu:

var menuItems = [
    {menuItem: 'home', url: '/'},
    {menuItem: 'depth', url: '/depth'},
    {menuItem: 'bolt circle', url: '/bolt_circle'}
];

Here's the Angular function that sorts the array and slices out the current page:

$scope.sort = function(){
    $scope.items = menuItems;
    for(i=$scope.items.length-1; i>=0; i--){
        var obj = $scope.items[i];

        if($location.path() === obj.url){
            $scope.items.splice(i, 1);
        }
    }

I'm relatively new to Angular and JavaScript, so I'm unsure why `menuItems` seems to be getting spliced along with `$scope.items`. Every time I navigate to a page, it gets removed from the menu until there are no links left. I thought creating a copy of the array each time the `sort()` function runs would provide a fresh array copy. I hope I've explained that clearly enough.

Answer №1

When you execute this:

$scope.items = menuItems;

you are not duplicating the contents of the menuItems array, but rather creating a new property items within the $scope Object that will reference the same array as menuItems. This indicates that $scope.items and menuItems point to the same array.

To generate a copy of the menuItems array, you should use this method:

$scope.items = menuItems.slice(0);

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 scenarios call for utilizing "dangerouslySetInnerHTML" in my React code?

I am struggling to grasp the concept of when and why to use the term "dangerous," especially since many programmers incorporate it into their codes. I require clarification on the appropriate usage and still have difficulty understanding, as my exposure ha ...

Deliver real-time updates directly to clients using Django Channels and Websockets

Currently, I am working on a page that needs to display live-updating data to the client. The rest of the website is constructed using Django framework, so my approach involves utilizing Channels for this purpose. The data that needs to be showcased is st ...

Reading the final element in the series with an IF statement

Something strange is happening with my code. I have a variable called racks_value that gets updated based on calculations performed on the page. Despite manually setting racks_value to 2 and confirming it with a console log, after running a series of IF st ...

Exception encountered with HTML5 cache manifest

I attempted to implement the application cache feature on my website, but I am facing a major issue. I only want to cache three specific files: style.css, favicon.ico, and script.js. The problem arises when the browser also caches other files such as inde ...

The result of Coordinates.speed is consistently null

I'm working on a project that involves changing the speed of background particles based on the user's device speed (like when they are in a car or bus). I thought the Geolocation API would be a perfect fit, specifically the Coordinates.speed prop ...

Leveraging the power of the .includes() method

Here is a question regarding the issue at hand. To tackle this problem, create a function called checkForPlagiarism with two parameters: an array containing responses from a specific individual and a string representing an external source. The function sh ...

I am in need of a efficient loader for a slow-loading page on my website. Any recommendations on where to find one that works

I'm experiencing slow loading times on my website and I'm looking to implement a loader that will hide the page until all elements are fully loaded. I've tested several loaders, but they all seem to briefly display the page before the loader ...

Utilizing v-if and splice on users to select items from v-model

After following a tutorial, I have the code snippet below that I would like to enhance: <div style="margin-top: 10px;"> v-for="task in taskItems" :key="task.id" <q-icon :name="task.icon"/> <div ...

Combining Versioning with BundleConfig.cs: A Comprehensive Guide

Encountering a recurring issue where changes made to CSS or Javascript files do not reflect in client browsers unless they manually refresh the page with ctrl+F5. This poses a challenge, especially in a school system with numerous users who may not be awar ...

A simple $scope link to the model

Here is my code snippet: .controller("GetAllAuthors", function ($scope, $http) { $http.get('http://localhost:8080/authors') .then(function (response) { $scope.authors = response.data; }); $scope.edit = fun ...

Unable to retrieve component name using React.Children

While working with react in the nextjs framework, I attempted to create my own dropdown component structured as follows: <Dropdown> <DropdownToggle>Action</DropdownToggle> <DropdownMenu> <DropdownItem>Menu 1</Dr ...

What is the best way to pass an array of 8-digit strings from an input in Angular to a Node.js backend?

I am currently facing a challenge where I need to pass an array of 8 digit strings from an Angular input to a Node.js endpoint. The method below works perfectly fine when passing a single string, but how can I handle an array of 8 digit strings as input? ...

Learn how to deactivate the pause button with just one click and re-enable it once the popup appears using Angular2 and Typescript

Can anyone assist with solving an issue I am facing with a timer and a pause button? I need the pause button to be disabled once clicked, until a popup appears, then it should become enabled again. My code snippet is provided below: HTML: <button md-i ...

Convert the 'value' attribute in HTML into a clickable link

Is there a way to make the output value of an HTML input field into a clickable link? Right now, it appears as follows: <input type="email" class="form-control" name="contactEmail" value="<?php echo $row_rsContactD ...

Error in Angular: Detected a circular dependency with $cookies

Encountered this error message: "Error: [$injector:cdep] Circular dependency found: $cookies <- $cookies <- AuthService" While using the code below 'use strict'; angular. module('core.auth'). factory('AuthService' ...

Transforming a base64 encoded string into a byte array

I have implemented a form where users can upload images to the page using an <input id = "fileLoader" type = "file" />. With JavaScript, I convert these uploaded images to base64 and send them to the server. On the server side, I need to decode this ...

Error message encountered when attempting to rotate an object in three.js: "Object is undefined"

Experiencing an "Undefined Object" error while attempting to rotate an object using three.js. Here is a snippet of the code in question: var object; function render() { renderer.render(scene, camera); } function animate() { object.rotation.x + ...

Searching through nested JSON data in an Angular application

I have a dynamic menu generated from a JSON object which looks like this: [ { "name":"Menu Item 1", "id":"8", "children":[ { "name":"Sub Menu 1-1", "id":"1", "children":[ ...

The identical items combined into a single array

I have a specific data structure that I am struggling to manipulate in JavaScript. The goal is to merge objects with the same invoice_nr into one array, while keeping other objects in separate arrays. const result = [ { invoice_nr: 16, order_id: ...

retrieve object from s3 using angular and open it as a pdf

I'm attempting to access a file from an s3 bucket using Angular and display it as a PDF. I have a node service set up to retrieve the object, which I then call from Angular. However, when I try to open the PDF in Angular, it appears as a blank (white) ...