Increasing numerical values within an array using JavaScript

My goal is to enhance the functionality of this visualization by being able to increase or decrease the nodes in the hidden layers. I have attempted to achieve this by adding the following code:

I am facing difficulties in adjusting the number of hidden layers as intended. As a result, I am seeking assistance. Can anyone guide me on how to accomplish this task and whether my approach is correct?

for (var i = 0; i < vm.hiddenLayersDepths[hiddenLayerLoop]; i++) {
    function minus() {
        vm.hiddenLayersDepths.map(function(val){return --val;});
        //Arrays.fill(vm.hiddenLayersDepths, vm.hiddenLayersDepths[0] - 1);
    }

    function plus() {
        if (vm.hiddenLayersDepths[0] < 5) {
            vm.hiddenLayersDepths.map(function(val){return ++val;});
            //Arrays.fill(vm.hiddenLayersDepths, vm.hiddenLayersDepths[0] + 1);
        }
    }
}

EDIT: My aim is to apply the + or - operation independently to each hidden layer.

Answer №1

To implement this functionality, you can use event binding by incorporating ng-click with your button elements and assigning corresponding methods within your controller.

<input type="button" value="-" id="moins" ng-click="vm.decrementHiddenLayerCount()">
<input type="button" value="+" id="plus" ng-click="vm.incrementHiddenLayerCount()">

In your controller, include the appropriate event handlers. Within these handlers, simply modify the value of the ngModel. This ensures consistency between your view and model. Below is a snippet showcasing where to place the event handlers.

app.controller('MainCtrl', function( $scope, $interval, $window, $q ) {
    var vm = this;

vm.incrementHiddenLayerCount = function() {
  const hiddenValue = vm.hiddenLayerCountSlider.value;
  if (hiddenValue < vm.hiddenLayerCountSlider.options.ceil) {
    vm.hiddenLayerCountSlider.value += 1;
    vm.hiddenLayersCount = vm.hiddenLayerCountSlider.value;
    draw();
  }
  }

  vm.decrementHiddenLayerCount = function() {
    debugger;
    const hiddenValue = vm.hiddenLayerCountSlider.value;
    if (hiddenValue > vm.hiddenLayerCountSlider.options.floor) {
     vm.hiddenLayerCountSlider.value -= 1;
    vm.hiddenLayersCount = vm.hiddenLayerCountSlider.value;
    draw(); 
    }
  }

You can access the code in action at: https://codepen.io/jasdeep7991/pen/mdJayKg

Answer №2

Utilizing Array.prototype.map()

By using the map() method, a new array is generated by applying a specified function to each element in the original array.

To update the values in the array as per the instructions provided for hiddenLayersDepths.

vm.minus = function() {
  vm.hiddenLayersDepths = vm.hiddenLayersDepths.map((i) => i - 1);
  draw();
};

vm.plus = function() {
  vm.hiddenLayersDepths = vm.hiddenLayersDepths.map((i) => i + 1);
  draw();
};

Experience how it works

https://codepen.io/aswinkumar863/pen/ZEGVYBp

Answer №3

If you want to specifically include or exclude nodes from a SINGLE layer, each layer should have its own set of plus and minus buttons. To achieve this, when creating these buttons for each index in hiddenLayersCount, it would be beneficial to establish a 'dataset' connection between the set of plus and minus buttons and the corresponding layer. For example, if there are two hidden layers, you would generate buttons similar to the following HTML structure after inserting them with javascript:

<div class"plus-minus-container">
  <input data-id="0" type="button" value="-" class="minus-button">
  <input data-id="0" type="button" value="+" class="plus-button">
</div>

<div class"plus-minus-container">
  <input data-id="1" type="button" value="-" class="minus-button">
  <input data-id="1" type="button" value="+" class="plus-button">
</div>

When adding these buttons using javascript, you can attach click listeners to each button so that they trigger functions like addNodeToHiddenLayer() or removeNodeFromHiddenLayer() within the vm scope (or wherever the vm.hiddenLayersDepths array is accessible).

function addNodeToHiddenLayer(event){
  const layerIndex = parseInt(event.target.dataset.id,10);

  if (vm.hiddenLayersDepths[layerIndex] < 5) {
    vm.hiddenLayersDepths[layerIndex] += 1;
  }
}

function removeNodeToHiddenLayer(event){
  const layerIndex = parseInt(event.target.dataset.id,10);
  if (vm.hiddenLayersDepths[layerIndex] > 1) {
    vm.hiddenLayersDepths[layerIndex] -= 1;
  }
}

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

Clear session data when logging out from a dropdown list

I have a header that appears on several of my web pages. It contains a dropdown menu that allows users to log out by selecting the "Logout" option. When a user clicks on "Logout", I want to destroy the session variables associated with their session. Is t ...

Can I use npm's jQuery in an old-school HTML format?

I am looking to incorporate jQuery into a project without having to rely on the website or CDN for downloading the library. As someone new to npm, I am curious to know if following these steps would be advisable or potentially problematic down the line. Wh ...

employing a directive to call upon a controller function triggering a straightforward alert display

I've been learning from this helpful tutorial and I want to make a change in my code so that an alert pops up when the button is clicked. If you'd like to see my code, here's the link to my fiddle I'm wondering how I can connect an el ...

Guide on inputting information into a dual-column table where one column is linked to the other

After successfully inserting data with hardcoded values to verify the relation between the 2 columns, I am now wondering if there is a way to reference the value of id in reply_id. This is how I manually inserted data: const { data, error } = await su ...

Searching for a document using the $eq operator in MongoDB within the context of Next.js - what is

In my Next.js code, I am fetching a document from MongoDB using a unique slug. Here is the code snippet: export async function getStaticProps(context) { const postSlug = context.params.postPage; const { db } = await connectToDatabase(); const posts ...

Should the page.js in a Next.js App router be a server component?

Is it standard practice in Next.js 13 and above (App router) for the page.js of all routes/folders to be a server component? I know that it can be a client component with use client, but is this advisable or are there potential issues during the build proc ...

The object returns true when the specified condition matches the key within the object

I need assistance with a specific object query. I am looking to execute the filter function in order to retrieve a list of keys from an object where the condition is true, as shown below: myObject = { key1: { name:"key1", select:true }, ...

ReactJS is struggling to showcase an image stored in the backend folder with the help of node

As a newcomer to React.js, I am facing a challenge with displaying images fetched from a database. Each action in the data has an array of images associated with it. The issue lies in not being able to properly display these images using the image tag due ...

Leveraging oEmbed - JSON data (within client-side JavaScript)

Is it feasible to utilize an oembed provider that solely produces json and xml outputs on the client side using javascript (through a $.ajax request to the provider)? Do we need to rely on oembed providers that enable a jsonp callback in javascript for th ...

What could be causing the "AJAX data not defined" error

Attempting to make an Ajax post request to the root directory on my Express server. By simply using the HTML form and submitting an artist name, I successfully receive a response back and can send the information to the client without any issues... As se ...

Issue with FullPageJS: scrollOverflow feature not functioning upon click event

I am currently working on a Fullpage.js instance that needs to be initialized with a click event and then destroyed when switching to another page, and vice versa. The scrollOverflow feature works perfectly as long as the #fullpage element is not hidden up ...

What is the best way to display a 404 error page for a nonexistent child page on a WordPress site?

After building our site with WordPress, I noticed that non-existent child page routes are not being redirected. For instance, let's say we have a page called about-us with the URL http://example.com/about-us. If I try to access a non-existing child p ...

trigger a p:ajax event by employing a right-click action

Currently, I am utilizing JSF and Primefaces 5.2. A peculiar observation I made is that when a commandLink is used with the onclick event and p:ajax, it creates a selection effect. <h:commandLink id="commandLink"> <p:ajax event="click"/> </ ...

The Autocomplete feature in Material-UI is not rendering any output

Within the render method of a class, an Autocomplete component is causing nothing to appear as rendered; once removed, everything else renders as expected. export default class Home extends Component { render() { return ( ... ...

AngularJS: Compile a particular template

One pre tag on the page contains dynamic text that is unknown during page load. This text may include ng commands, as shown below: <pre> Hello <span ng-click="test('args')">world</span> angular-JS! </pre> Since these ...

asp.net website fully compressed using GZip

I am currently developing a Single Page Application (SPA) and I have encountered an issue with the size of my JavaScript files, which are about 300 KB. Additionally, the web services (.asmx files) that generate jsdebug files add another 350 KB to the bundl ...

XSRF Cookies are failing to attach to the request header when an https iframe is being loaded on an http site

Recently, I successfully implemented XSRF protection on a website using MVC and AngularJS. The secure site can be accessed in two ways: through a direct post or within an iframe. Below is the code snippet: .config(function ($httpProvider) { $h ...

Using TypeScript with React: Initializing State in the Constructor

Within my TypeScript React App, I have a long form that needs to dynamically hide/show or enable/disable elements based on the value of the status. export interface IState { Status: string; DisableBasicForm: boolean; DisableFeedbackCtrl: boolean; ...

What is the best way to incorporate and organize the templateHyper folder within an established web project directory?

Can anyone offer advice on how to properly integrate and organize the 'templateHyper' (Bootstrap template) folder within my web project? I've been developing a project using C#, JavaScript, HTML, and Bootstrap's templateHyper. I'm ...

The Shopify storefront API's create cart mutation generates an HTML response when called

I recently started developing an e-commerce website using Next.js and Shopify's storefront API. I have successfully set up the connection and can list all the products from the API. However, I encountered an issue when attempting to add a product for ...