What is the best way to transfer a variable selected from an option form to my Controller?

Could someone please assist me in retrieving the selected value onchange of a dropdown box and then using that value as a variable in my controller? I am facing an issue where the $ColorPicked variable does not resolve in the $scope.base = response.data.type.$ColorPicked; statement. However, if I manually input "Red" instead of $ColorPicked, it works perfectly fine.

I am fairly new to Angular and JavaScript, so I apologize for any ignorance on my part. Despite extensively searching online, I have been unable to find a clear solution to this problem.

INDEX.HTML
<h3>Color:</h3>
<select class="formBoxes" id="ColorPicked">
<option value="Red">Redd</option>
<option value="Blue">Blue</option>
<option value="Green">Green</option>
</select>

SCRIPT.JS
$ColorPicked = "Red";

var app = angular.module("computer",['ngRoute'])
.config(['$routeProvider', function($routeProvider){
  $routeProvider.
    when('/main',{
       templateUrl: 'archetype.html',
      controller:'MainCtrl'
    }).
    otherwise({redirectTo:'/main'})
}])

.controller('MainCtrl', ['$scope', '$http', function($scope, $http){
  $http.get('archetype.json').then(function(response){

    $scope.base = response.data.type.$ColorPicked;

    ;
  });
}]);

Answer №1

To link the chosen value to the controller's property, you must utilize ng-model. If you wish to set the select input to a model value initially, then use ng-options

<select ng-model="selectedColor"
        ng-options="opt.value as opt.label for opt in opts">
</select>

In your controller, you should have the following in your scope:

$scope.opts = [
    { value:'red', label:'Red' },
    { value:'blue', label:'Blue' },
    { value:'green', label:'Green' },
]

$http.get(...).then( function( response ){ 
    $scope.selectedColor = response.data.type.$colorPicked;
})

Answer №2

If you want to achieve this, there are two important steps you need to follow:

(i) Ensure that you have a $scope variable set for the ColorPicked so that you can establish a default selection.

(ii) Make sure to include ng-model which will be linked to the variable. Then pass the selected Color to the function by utilizing the ng-change directive.

HTML:

 <select ng-model="ColorPicked" ng-change="setItem(ColorPicked)">
      <option>Red</option>
      <option>Blue</option>
      <option>Green</option>    
  </select>

Controller:

function MyCtrl($scope) {
    $scope.ColorPicked = "Red";    
    $scope.setItem = function(opt) {
    $scope.base =opt;
  }
}

DEMO

Working Demo tailored to your needs

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

Parsing form array/bracket fields into actual arrays with ExpressJS

Is there any middleware available or code snippets that can help me to convert form fields with square brackets (e.g. 'contact[21][name]') into actual arrays for ExpressJS 3? I am looking for something like this: for(key in req.body){ if(ke ...

Time picker in Bootstrap - Ensuring end time is not earlier than start time validation

How to prevent users from selecting a past time for the end time in Bootstrap time picker with start time validation <html> <head> </head> <body> <link href="https://maxcdn.bootst ...

What is the best method for storing a list of present and absent students in a database to effectively manage attendance records?

I am struggling to save the daily present/absent details of students in a database for my project. Despite obtaining the student's name and roll number from another table, I can't seem to figure out how to save this information effectively. Any a ...

Is there a method to generate a texture on-the-fly and bind it to a Mesh object in three.js?

I'm currently exploring ways to dynamically generate a texture at run-time, which can then be loaded and applied to a material. For example: Imagine if, when a user inputs "hello world", a basic 128px x 128px white image (bitmap) is generated in the ...

The SimpleHTTPServer is causing Google Maps Places Autocomplete feature to malfunction

Currently, I am implementing a location search feature along with form auto-fill using the google.maps.places.Autocomplete functionality. While accessing the HTML file directly (file:///location.html), everything is functioning as expected. However, when ...

Limiting Velocity in a Two-Dimensional Spacecraft

Like many others diving into the world of programming, I decided to challenge myself with a spaceship game project. At this point, I have successfully incorporated parallax stars and other essential features expected in a space-themed game. The spacecraft ...

Retrieving child component's data property in Vue 3 using TypeScript and Composition API

I have set up two components: a parent and a child. App.vue //Parent <template> <div class="common-layout"> <Container> <Header><center>Vue JS 3 (Composition API and )</center></Header> ...

What is the best way to sort through custom components within children in Solid JS?

I have been working on developing a scene switcher for my personal application, and I thought of creating a custom component called SceneSwitcher. Inside this component, I plan to add various scenes that can be rendered. Here's an example: <SceneSw ...

convert HTML string into a React component using a customized parser

I received an HTML string from the server that looks like this: <h1>Title</h1>\n<img class="cover" src="someimg.jpg">\n<p>Introduction</p> My goal is to modify the HTML by replacing the <img class="cover" src="s ...

Pattern matching to verify a basic number within the range of [0-6]

const number = '731231'; const myRegex = /[0-6]/; console.log(myRegex.test(number)); Could someone provide some insight into this code snippet? In my opinion, the regular expression [0-6] should only match numbers between 0 and 6. However, i ...

JavaScript HTML content manipulation

Why doesn't this code work? innerHTML cannot handle something so complex? <html> <head> <script type="text/javascript"> function addTable() { var html = "<table><tr><td><label for="na ...

What is the best way to create an array within an object during the parsing process

When working with a JSON object, I need to assign a value stored in the session against an ID. The JSON data is as follows: [ { "id": "a", "text": "a", "icon": true, "li_attr": { "id": "a" }, "a_attr": { "href": "#" ...

establishing a connection between an AngularJS application and an ExpressJS backend

I am currently working on developing an application that utilizes AngularJS for the front end and a REST API using Express.js. Both projects were created with Yeoman, with my Angular app running on localhost:9000 and the Express app running on localhost:30 ...

Having difficulty displaying a loading message upon generating a new screen

Recently, I encountered a challenge on my website where I needed to perform a lengthy computation upon clicking a button in client-side JavaScript. I wanted to display a loading message while the computation was running, so I implemented the following code ...

What does the error message "TypeError: Bad argument TypeError" in Node's Child Process Spawn mean?

Every time I execute the code below using node: var command = "/home/myScript.sh"; fs.exists(command, function(exists){ if(exists) { var childProcess = spawn(command, []); //this is line 602 } }); I encounter this error: [critical e ...

Implementing a Dropdown Menu Within a React Form

I am currently working on setting up a reservation system for rooms. I want to include 2-4 different room types and incorporate a dropdown menu instead of manual input. I am using the guidance provided here. I attempted to use <Form.Select...>, but i ...

Is there a way to create an HTML select element where each option has a unique background color, and will display properly

I want to create multiple HTML select elements with unique background colors for each option: <select runat="server" id="select"> <option value="A">White</option> <option value="B">Red</option> <option value="C">Yellow& ...

Sticky Navigation Error: Issue with accessing property 'top' of an undefined element

I'm currently working on incorporating a feature into my website where the navigation style changes as you scroll through different sections. The main distinction I've noticed is that I am developing a sticky navigation bar that becomes fixed on ...

Are you initiating several Ajax requests simultaneously?

What is the best approach to updating multiple sections of a page using Ajax? I am working with two divs and two PHP files. My goal is to use jQuery Ajax to populate one div with data received from one PHP file and the other div with data from the second ...

Error in Leaflet: Uncaught TypeError: layer.addEventParent is not a function in the promise

Having trouble with Leaflet clusterGroup, encountering the following error: Leaflet error Uncaught (in promise) TypeError: layer.addEventParent is not a function const markerClusters = new MarkerClusterGroup(); const clusters = []; const markers = []; co ...