Creating a switch case statement within a specific scope

How can I generate cases using $scope.type[i] (a JSON array from the database)?

 $scope.type = [{nomcarac: "phone"}, {nomcarac: "shoes"}];

  $scope.getValuesList = function(item) {
    switch (item.type){
      case 'phone': 
        item.valuelist = angular.copy($scope.phonelist);
        break;
      case 'shoes': 
        item.valuelist = angular.copy($scope.shoeslist);
        break;
      default:
        item.valuelist = [];
        break;
    }
  };

Answer №1

$scope variables function much like regular javascript variables. To access sub-levels, simply use a variable in this manner:

item.valuelist = angular.copy($scope[item.type + 'list']);

If you're concerned about invalid strings, you can always check for null later on.

Answer №2

I am optimistic that it will meet your expectations :

var myApp = angular.module('myApp',[]);

myApp.controller('MyCtrl', function($scope) {
    $scope.type = [{nomcarac: "phone"}, {nomcarac: "shoes"}];

    $scope.getValuesList = function(item) {
      switch (item.nomcarac) {
        case item.nomcarac:
          item.valuelist = angular.copy($scope.phonelist);
          break;
        default:
          item.valuelist = [];
          break;
      }
    };
    
    for (var i in $scope.type) {
    $scope.getValuesList($scope.type[i]);
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-controller="MyCtrl" ng-app="myApp">
</div>

Answer №3

Ensure to provide the correct object value to the switch statement to match the cases. In the example below, inputting either "phone" or "shoes" will trigger the switch.

var myApp = angular.module('myApp', []);
    myApp.controller('ctrl', ['$scope', function ($scope) {
    $scope.type = [{nomcarac: "phone"}, {nomcarac: "shoes"}];

  $scope.getValuesList = function(index) {
    switch ($scope.type[index].nomcarac){
    
      case $scope.type[index].nomcarac: 
        $scope.valuelist = $scope.type[index].nomcarac +" " + "worked";
        console.log($scope.valuelist);
        break;
      default:
        $scope.valuelist = "Nothing worked";
        break;
    }
  };
  for(var i=0;i<$scope.type.length;i++)
    $scope.getValuesList(i);
   }]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="ctrl">
</div>

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

Upon clicking the IconButton within the ImageListItemBar, reveal the image within a Material-UI Dialog

import * as React from 'react'; import Box from '@mui/material/Box'; import ImageList from '@mui/material/ImageList'; import ImageListItem from '@mui/material/ImageListItem'; import ImageListItemBar from '@mui/m ...

Having trouble passing data between view controllers

In my AngularJS application, I have a table column in main.html that is clickable. When clicked, it should redirect to a new customer page with the value of the column cell as the customer's name. There is a corresponding service defined for the app m ...

Navigating nested JSON structures in React JS - a guide to iteration

I am struggling with efficiently navigating through a JSON file that is obtained by making an API call. My intention is to utilize this JSON data for mapping purposes and generate components based on it. Issue: How can I effectively traverse nested JSON d ...

stopping action when hovering

Looking for some assistance with my javascript function that scrolls through an array of images on a set interval. I want to enhance it by pausing the rotation when hovering over any of the images. Javascript (function() { var rotator = document.getE ...

Distance between cursor and the conclusion of the text (autofocus)

I discovered a method to automatically position the cursor at the end of a string using autofocus: <input name="adtitle" type="text" id="adtitle" value="Some value" autofocus="" onfocus="this.setSelectionRange(this.value.length,this.value.length);"> ...

Is there a way to store a SAFEARRAY (an array of bytes) into an HTML hidden field?

Is there a way to extract an array of bytes from an active-x component, save it in an html-form input hidden field, and then send it to the server using form-submit? I'm not sure how to accomplish this. MIDL: HRESULT Data([out, retval] SAFEARRAY(VAR ...

Error: JSON parsing error due to unexpected token C at the beginning of the string

When using ajax and json formatting, I am encountering this message. In PHP, the code array("message" => "Success", "data" => $data) is displayed successfully. However, it is not able to callback to ajax. How can I resolve this issue without deleting ...

Accessing the current instance in Vue when triggered by a checkbox event

Recently, I tested out a to-do-list application built in Vue that has a checkbox feature to mark completed items. I'm looking for a way to access the current instance from the checkbox event. Here's what I've accomplished so far: myObject ...

Sending a JSON stringified JavaScript object to a server: A step-by-step guide

I am currently working with VB.Net and MVC 5. In my project, I have an object that I created using javaScript: var myEdits = { listOfIDs: [], listOfValues : [] }; My goal is to send this object to the controller an ...

Steps to remove a package from the npm registry

Is it feasible to eliminate or erase a complete module from the npm registry? Please be aware that using npm -f unpublish does not permit the deletion of packages older than 24 hours. ...

Retrieving JSON data to create and showcase an HTML table

Can you help me figure out what's going wrong with my code? I have an HTML page with a table where I fetch data from the web in JSON format using JavaScript. The logic works perfectly when the fetch code is let to run on its own, but when I try to ex ...

Calculating the time difference in days, hours, minutes, and seconds between two UNIX timestamps

I have a special occasion coming up, and the date and time for this event are stored in a Unix timestamp format. Instead of relying on a plugin like modern.js, I am trying to figure out the time difference between today's date and the event date usin ...

Activate Jquery to display the submenu when clicked and conceal any other open submenus at the same time

I'm trying to create a responsive menu with menus and submenus using JQuery. However, as a newbie to JQuery, I'm struggling to hide a previous submenu when displaying another one. Here's the CodePen link Below is the HTML code: <nav cl ...

Angular.js has a unique filter that allows users to customize the date format to their preference

My upcoming event is happening on "endDate": "2014-11-30 01:00:00.0", in JSON format. I want to display it as 30 Nov 2014. I attempted to display it using: {{ phone.endDate | date:'medium' }} within an HTML document. Unfortunately, it is sti ...

Steps to saving an item in the browser's local storage in real-time

My current challenge involves constructing a child array nested within a data array. When a user clicks on buttons to input data, the information does not get saved in localStorage in real-time. For example, if there are 4 buttons with different user input ...

What is the best way to access the original observed node using MutationObserver when the subtree option is set to

Is there a way to access the original target node when using MutationObserver with options set to childList: true and subtree: true? According to the documentation on MDN, the target node changes to the mutated node during callbacks, but I want to always ...

Issue encountered while requesting data from API in ReactJS

I've been trying to fetch data from using the react useEffect hook. However, instead of displaying the data, I keep getting an error message that says, "Error: Objects are not valid as a React child (found: object with keys {number, name}). If you me ...

What is the best way to organize objects in a 2D game?

I am currently working on a unique perspective-based 2D/3D game using javascript. In the image below, you can see the X and Y-axis that I have implemented for this project. My question: On the map, I have several objects labeled as "1" and "2" with prope ...

Looking for a Plugin that Can Responsively Display Images in a Vertical Layout - Does One Exist using Jquery

Looking for a gallery slider plugin that is responsive both horizontally and vertically. Have tried Flexslider1/2, Galleria, and others but they do not adjust to vertical resizing. Changing the CSS did not help. If you resize the browser horizontally with ...

Retrieving a boolean value (from a JSON file) to display as a checkbox using a script

Currently, I am utilizing a script to fetch data from a Google Sheet $.getJSON("https://spreadsheets.google.com/feeds/list/1nPL4wFITrwgz2_alxLnO9VBhJQ7QHuif9nFXurgdSUk/1/public/values?alt=json", function(data) { var sheetData = data.feed.entry; va ...