Utilizing a repetitive function in AngularJS

In my controller, I have a repetitive function that looks like this:

//FUNCTION 1

$scope.selectedage = [];
$scope.pushage = function (age) {
    age.chosen = true;
    $scope.selectedage.push(age);
    console.log($scope.selectedage);
};
$scope.unpushage = function (age) {
    age.chosen = false;
    var index=$scope.selectedage.indexOf(age)
    $scope.selectedage.splice(index,1);     
    console.log($scope.selectedage);
}


//FUNCTION 2

$scope.selectedgender = [];
$scope.pushgender = function (gender) {
    gender.chosen = true;
    $scope.selectedgender.push(gender);
    console.log($scope.selectedgender);
}; 
$scope.unpushgender = function (gender) {
    gender.chosen = false;
    var index=$scope.selectedgender.indexOf(gender)
    $scope.selectedgender.splice(index,1);     
    console.log($scope.selectedgender);
}

This code is repeated 8 times for 8 different arrays. Is there a way to write it once and reuse it by just changing some values?

Answer №1

A useful function can be created that takes a specified value (container) as an input to write the desired "value". For example:

$scope.addToList = function(container, value){
    value.selected = true;
    container.push(value);
    console.log(container);
}

$scope.removeFromList = function(container, value){
    value.selected = false;
    var index = container.indexOf(value)
    container.splice(index, 1);     
    console.log(container);
}

//example
$scope.addToList($scope.chosenItems, "Apple");
$scope.addToList($scope.chosenFruits, "Banana");

Answer №2

function updateItemStatus(item, key, newStatus){
 item.status = newStatus;
 if(newStatus == true){
   $scope[key].push(item);
 } else {
   var index=$scope[key].indexOf(item)
   $scope[key].splice(index,1); 
 }
 console.log($scope[key]);
}

updateItemStatus(currentItem, 'selectedAge',true);

Revamping code for potential reuse in a service

    (function() {
    'use strict';

    angular
        .module('myApp')
        .factory('ItemManager', ItemManager);

    ItemManager.$inject = [];

    /* @ngInject */
    function ItemManager() {
        var service = {
            toggleItemState: toggleItemState
        };
        return service;

        ////////////////
        /*
        itemContainer - akin to scope object
        item - item to manipulate
        itemKey - identifier for the item 
        chosenStatus - true for addition, and false for removal
        */
        function toggleItemState(itemContainer, item, itemKey, chosenStatus) {
            item.status = chosenStatus;
            if (chosenStatus == true) {
                itemContainer[itemKey].push(item);
            } else {
                var index = $scope[itemKey].indexOf(item)
                itemContainer[itemKey].splice(index, 1);
            }
            console.log(itemContainer[itemKey]);
        }
    }
})();

To use it in your controller, simply do this:

ItemManager.toggleItemState($scope, itemToUpdate, 'selectedAge', true);// add item
ItemManager.toggleItemState($scope, itemToUpdate, 'selectedAge', false);// remove item

I've altered the function name and variable naming for improved clarity. I hope this revised version serves you well.

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

Attempting to adjust the width of a text animation loaded with jQuery using Textillate, but encountering difficulties

I found a captivating animation on this website: http://codepen.io/jschr/pen/GaJCi Currently, I am integrating it into my project. #content { position: relative; margin-left: auto; margin-right: auto; width: 1000px; height: 700px; } ...

What is the process for creating facial geometry in threeJS using the scaledMesh output from face detection with TensorFlow in JavaScript?

I am trying to generate a 3D model of a detected face using ThreeJS and the Tensorflow library for detecting faces. However, when I utilize BufferGeometry to create the face geometry, the results are not as expected. https://i.sstatic.net/DsPox.png Below ...

The Bootstrap accordion feature or show/hide function is experiencing issues when dealing with dynamically created elements in jQuery

When interacting with items in my sample application, a pop-up displaying the item's description should appear. However, attempts to use Bootstrap accordion or hide and show features were unsuccessful, only jQuery delegate event handlers worked. In g ...

How can a single value (the clicked one) be retrieved from a for loop using addEventListener in a Django project with JavaScript

Struggling to integrate JS into my Django project, I received the following message in the console: HTMLCollection(2) [p.currency-one, p.currency-one] HTMLCollection(2) [input.amount-one, input.amount-one] app.js:21 Uncaught TypeError: c1.addEventListener ...

Troubleshooting the Timepicker import issue in ant design version 5.0.3

After updating ant design to version 5.0.3, I encountered the Uncaught Error: Cannot find module 'antd/lib/time-picker/style' at webpackMissingModule issue. Any suggestions on how to resolve this? I am seeking a solution for the error coming fro ...

Rails assets folder is not directed to the specified directory in the layout file

I have a dilemma in the application layout where I'm referencing assets (js, css, and img) in the public/assets/... directory. For example: <link href='assets/images/meta_icons/apple-touch-icon-144x144.png' rel='apple-touch-icon-pre ...

Having trouble getting the onclick function to work in order to switch out the images

This is the HTML code that I used Here is the JavaScript code, but the onclick function seems to not be working ...

Does anyone know how to disable JavaScript on a webpage specifically for a Blackberry 8300 browser?

I am facing an issue with my JavaScript on the BlackBerry 8300, where the page renders differently when JavaScript is disabled. I would like to find a way to make sure that the "JavaScript disabled" version of the page appears for users using BlackBerry 83 ...

Rendering a .stp file with Three.JS

I am in search of a way to create a basic 3D model preview using a '.stp' file. During my research, I came across the Three JS library. This library enables the rendering of 3D files similar to this example: I am eager to incorporate this funct ...

Experiencing a missing handlebars helper error when utilizing a helper within partials in express-handlebars

I have set up custom helpers using express-handlebars like this: const { create } = require("express-handlebars"); // Configuring the handlebars engine const hbs = create({ helpers: require("./config/handlebars-helpers"), }); app.engi ...

What is the best way to ensure a texture is always facing the camera?

Latest Update: We have created a new demo to showcase the desired outcome. The demo includes an invisible skydome, a cubecamera, and an environment map. However, it is important to note that these techniques should not be utilized for the reasons previous ...

Exploring the iteration of JSON objects within an array using AngularJS

My auto search module has the following JSON structure. I need to iterate through an array of JSON objects and use keys and values as required. I have attempted the code below. However, with the provided JSON object, I am able to retrieve the key but not ...

Encountering surprising outcomes with jQuery AJAX POST functionality when interacting with PHP script

I have created a form where I am expecting to receive post results in my div with the ID "response". <!DOCTYPE html> <html> <head> <title>AJAX POST</title> <script src="jquery.js"></script> <script> $(do ...

Retrieving a function's output in React

Upon attempting to retrieve and log the res.data from my function, I encountered an issue where it returned as undefined. However, when I logged it from within the function, the result appeared normal. const getDefaultState = () => { axios .get ...

Validating Forms and Files with jQuery and C# in ASP.NET

I'm facing some uncertainty on how to effectively combine jquery/javascript with C#. My task is to incorporate a javascript confirm popup into a file upload form, but the confirm prompt should only appear if specific criteria are not met. There are 4 ...

Troubleshooting the issue with UI-Router AngularJS controller not functioning properly in a

Trying to grasp the ins and outs of UI-Router in conjunction with Angular has proven to be quite challenging for me. In my setup, there's an index: <body> <div ui-view></div> <!--Location of file holding app--> <scri ...

Avoid having the java applet destroyed when the container is hidden

I am working with multiple DIVs, each containing text, a java applet (unfortunately...) and buttons. I am currently creating a search function to dynamically show and hide these DIVs. However, whenever I use display:none on a DIV, the applet inside it se ...

Mastering Light and Camera Selection in Three.js

Question, In the editor found at this link, you can click on a light or camera to select it. I am familiar with using raycaster.intersectObjects(objects) to select meshes, but how can I achieve the same result for lights and cameras which do not have mesh ...

Enhance the flight experience of a helicopter with jQuery game by adding smoother controls

I'm currently experimenting with creating a basic game. In this game, the user controls a helicopter and can fly it up and down. Although I have successfully implemented the basic functionality where holding the screen makes the helicopter ascend an ...

Troubleshooting: React Testing Library Issue with Updating Material UI DatePicker Input Content

I'm attempting to update the value of the Material UI Datepicker Input using React Testing Library. Unfortunately, I have not been successful with the fireEvent.change() method. import React from "react"; import { render, screen, waitFor, fi ...