How to access the selected value of an Angular JS dropdown within the controller?

I need assistance with selecting a dropdown value in AngularJS and saving it in a service to be used on another view for displaying the user's selected value along with the full dropdown. However, I am encountering an issue where the selected value is showing as undefined when I try to log it inside the controller. Any guidance on how to proceed would be greatly appreciated.

<td>
  <select name="systems" class="pulldown1" id="systems" ng-model="system.selectedOption" ng-controller="EurexController" required ng-options="option.name for option in system.availableOptions track by option.id" ng-init="system.selectedOption=system.availableOptions[0]" ng-change="changed()"> </select>
</td>

Controller code:

$scope.system = {
  availableOptions: [{
    id: 'Domestic 1',
    name: 'Domestic 1'
  }, {
    id: 'Domestic 2',
    name: 'Domestic 2'
  }, {
    id: 'Global',
    name: 'Global'
  }, {
    id: 'Far East',
    name: 'Far East'
  }],
  // selectedOption: {id: 'Domestic 1', name: 'Domestic 1'} //This sets the default value of the select in the ui
};

I have also attempted using the selectedOption method recommended on the AngularJS website but without success.

console.log($scope.system.selectedOption);
console.log(systems);

Answer №1

When using the ng-controller attribute, it is advisable to place it on a container element rather than directly on elements like <select>. This allows you to utilize the controller across your entire view instead of restricting it to just the <select> element. The reason why your console.log(systems); returns undefined is because the variable systems is not defined within the controller context. It's best to refrain from using ng-init unless absolutely necessary, as explained in the documentation. Below is an updated example based on the code snippet provided:

angular.module('app', [])
  .controller('ctrl', function($scope, myService) {
    $scope.system = {
      availableOptions: [{
        id: 'Domestic 1',
        name: 'Domestic 1'
      }, {
        id: 'Domestic 2',
        name: 'Domestic 2'
      }, {
        id: 'Global',
        name: 'Global'
      }, {
        id: 'Far East',
        name: 'Far East'
      }]
    };

    $scope.system.selectedOption = {};
    
    $scope.optionChanged = function() {
      myService.optionValue = $scope.system.selectedOption;
      console.log($scope.system.selectedOption);
    }
  })
  .controller('ctrl2', function($scope, myService) {
    $scope.myService = myService;
  })
  .service('myService', function() {
    var _optionValue = {};
    return {
      get optionValue() {
          return _optionValue;
        },
        set optionValue(value) {
          _optionValue = value || {};
        }
    }
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<div ng-app="app">
  <div ng-controller="ctrl">
    <h2>ctrl</h2>
    <div>
      <select ng-model="system.selectedOption" ng-options="option as option.name for option in system.availableOptions" ng-change="optionChanged()">
        <option value="">Please select</option>
      </select>
    </div>
    <div>
      Selected option: {{ system.selectedOption | json }}
    </div>
  </div>
  <div ng-controller='ctrl2'>
    <h2>ctrl2</h2>
    <div>
      {{ myService.optionValue }}
    </div>
  </div>
</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

How to automatically embed a p5.js canvas into an HTML canvas with the drawImage() method

Whenever I attempt to draw the p5.js canvas into an HTML canvas using drawImage(), I always encounter this error: Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type ' ...

How can I optimize the usage of npm as a front end package manager in my Node.js application?

As I delve into learning Node.js and Express, my goal is to incorporate Angular for the frontend. While I am comfortable using npm for managing Node.js modules, I am facing a dilemma when it comes to handling frontend dependencies. Most tutorials suggest u ...

Creating a switch statement that evaluates the id of $(this) element as a case

I have a menu bar with blocks inside a div. I am looking to create a jQuery script that changes the class of surrounding blocks in the menu when hovering over a specific one. My idea is to use a switch statement that checks the ID of $(this) and then modif ...

Tips for determining if a text box is clean or soiled

Below is the code snippet in HTML that I am working with: <th style="width:90px"> <span>ID</span><img class="serverRP_ajax-loader" src="loader_green_32.gif" /><input type="text" id="abc" ng-model="rpFilter.ResourcePlanID.valu ...

Is it possible to utilize jQuery to add 'a' attributes in HTML5?

Here is a snippet of code that works with Chrome and Firefox browsers: HTML: <a id="savefile""> Save transferred file </a> Javascript: // event is returned by a readAsDataURL() var save = document.getElementById('savefile'); s ...

Multiple tabs open with inactive sessions

I am currently facing an issue regarding user idle timers in jQuery. I have implemented a timer that logs the user out of the app if they are inactive for 30 minutes, and this works perfectly with one browser tab open. However, I now need to extend this ...

Nested List in Vuetify Components

I am struggling to create a deeply nested list with more than three levels in Vue.js. When I attempt to nest children items inside a child item using v-list, nothing is displayed. Is it even feasible to have such a complex nested list structure in Vuetify ...

Identifying overflow of text or elements in JavaScript during execution

The website I'm working on has a unique design that requires users to scroll horizontally using the Arrow Keys instead of swiping. To achieve this, I must constantly check for overflow in text or elements each time a new page is loaded, and if necessa ...

The function get_the_category() is not compatible when used within the <figcaption> element

I'm encountering a strange issue. I'm attempting to incorporate a javascript gallery from this site into my WordPress theme. My goal is to show the post category as a figcaption, but when I insert my PHP code inside, it doesn't function prop ...

selenium.common.exceptions.JavascriptException: Alert: ReferenceError: The variable has not been declared

' ct1 = df2[(df2['HomeTeam'] == at1)]['AwayTeamScore'].to_string(index=False) result_away = np.round(ct1, decimals=3)' Output: '0.938031' While working on the following code, I encountered an issue: 'javaSc ...

Having trouble applying filters in AngularJS Controller

Hey there, just diving into Angular here. Currently working with AngularJS 1.2.4 and running into an issue when trying to inject a filter in my controller. The error message I'm getting is: Error: error:unpr Unknown Provider Unknown provider: sen ...

What is the process for taking a website project running on localhost and converting it into an Android web application using HTML, CSS, and JavaScript

Looking for recommendations on how to create an Android web application using HTML, CSS, and JavaScript. Any suggestions? ...

Choose an option using jQuery with the ability to navigate to the previous or next

I encountered a bug when I tried to click the next or previous button. Below is the HTML code snippet: $("#nextPage").click(function() { $('#pagination option:selected').next().attr('selected', 'selected'); console.log( ...

"Handling API Calls with AngularJS: Dealing with the [object object] Response

Looking for some guidance on pulling a list of articles from the NPR API. I have a functioning URL that returns JSON data. However, in my controller code, I seem to be having trouble accessing the object. When I use console.log to check, it just shows [obj ...

Variations in speed with closely related jQuery expressions in Internet Explorer

When running in Internet Explorer, test the performance of executing an expression like: $('div.gallery div.product a"); against a similar expression: $('div.gallery').find("div.product").find("a"); It has been found that sometimes the s ...

The MongoDB search results did not yield the desired entries

i am attempting to display specific data for a user using req.session.user and passing the ID to the criteria i am constructing. (each entry also has a user field so i can match) but unfortunately, it is not functioning as expected. The Service : async fu ...

Refreshing a Web Page with JavaScript

I'm currently facing an issue with my Rails application that includes JavaScript. The JavaScript works fine when the document is initially loaded, but I need it to reload whenever a new page is visited. Is there a way to achieve this without having to ...

Expand the data retrieved from the database in node.js to include additional fields, not just the id

When creating a login using the code provided, only the user's ID is returned. The challenge now is how to retrieve another field from the database. I specifically require the "header" field from the database. Within the onSubmit function of the for ...

Using Jquery for a Second Timer

I have a jQuery function that looks like the one below. The result is displayed in a span, but when the page is reloaded, this span briefly disappears and then reappears. Is there a way to prevent this from happening? I need it to stay visible at all tim ...

Comparison of Hmac implementation in MIGS payment between PHP and Node.js

I'm in the process of transforming the MIGS payment gateway code from PHP to NODE.js. Everything is working smoothly except for the generation of the hmac hash code. PHP CODE strtoupper(hash_hmac('SHA256',$this->hashInput, pack("H*",$t ...