Tips for obtaining an ID from a dropdown menu and establishing a default value at the top

My code snippet is currently displaying null for the card_id, but I want to ensure that the id and is_default card are displayed on top. How can I achieve this? Whenever I use ng-click, the result displayed is as shown below. My goal is to obtain the selected card_id.

<select ng-model="approvedinvoicesCtrl.currentcard.card_id" >
    <option ng-value="item.card_id"  
        ng-repeat="item in approvedinvoicesCtrl.current_job.cards" 
        ng-selected="item.is_default">{{item.brand +'      '+ item.last_digits}}
    </option>
</select>

Result:

card_id: "",
charge_description: "ff", 
charge_type: "Credit Card Payment"

Answer №1

Utilize ngOptions (go to the linked page for more examples) to configure the options for the select list and employ ng-bind to showcase the card_id in the DOM. The functional approach is also used to designate the current card by utilizing Array.prototype.find(). Refer to the example below:

angular.module('app', [])
  .controller('ctrl', function($scope) {
    $scope.approvedinvoicesCtrl = {
      current_job: {
        cards: [{
          card_id: 1,
          brand: "BMW",
          last_digits: "Z3",
          is_default: false
        }, {
          card_id: 2,
          brand: "Mercedes",
          last_digits: "713",
          is_default: true
        }, {
          card_id: 3,
          brand: "Audi",
          last_digits: "Q4",
          is_default: false
        }]
      }
    };
    //set the model/default selected item
    $scope.approvedinvoicesCtrl.currentcard = $scope.approvedinvoicesCtrl.current_job.cards.find(CardIsDefault);
    $scope.log = function() {
      console.log('card_id: ', $scope.approvedinvoicesCtrl.currentcard.card_id);
    };
  });

function CardIsDefault(card) {
  return card.is_default;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
  <div>Selected brand: <span ng-bind="approvedinvoicesCtrl.currentcard.brand"></span>
  </div>
  <div>Selected Id: <span ng-bind="approvedinvoicesCtrl.currentcard.card_id"></span>
  </div>
  <select ng-options="item.brand+' '+item.last_digits for item in approvedinvoicesCtrl.current_job.cards" ng-model="approvedinvoicesCtrl.currentcard"></select>
  <button ng-click="log();">show card_id</button>
</div>

Answer №2

To achieve this, make use of the ng-init and ng-options directives as shown below:

<select ng-init="initialSelection = choices[1]" 
        ng-model="initialSelection" 
        ng-options="choice for choice in choices">
</select>

The ng-init directive helps in setting a default value for the selection

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

Trouble with pinch zoom functionality in a Vue component

I have a Vue component that allows me to zoom in on an image using the mouse wheel, but I'm experiencing strange behavior with pinch zoom. When I place two fingers far apart on the screen, it zooms in significantly, and when I bring them closer togeth ...

Create an array containing the data returned from the Observable<{string, number, string}[]> stream

Currently I am working on creating an Angular 9 app, and I need to return an array with my response. Within the service class, I have a method like this: getReport(startDate: string, endDate: string) { return this.http.get<ReportReport>( ...

Multiple renderings of React useEffect

I am currently exploring Hooks. I previously implemented a project using componentDidMount. Now, as I dive into learning about hooks, I am in the process of rewriting this project to incorporate hooks. My initial goal is to fetch data and display it on th ...

The controller is failing to trigger the "then" function with the deferred object from the mock

I am currently working on mocking a method within a service that returns a promise. The controller's code snippet is as follows: app.controller('MainCtrl', function($scope, foo) { var self = this; this.bar = ""; this.foobar = function() { ...

The ng-selected attribute is nonfunctional, however, it can modify an option to be selected by using selected="selected" when paired with

When I check my HTML code, I notice that even though the value of one of the <option> elements changes to `selected="selected"`, it is not actually selected when viewed. Below is the relevant section of my code: <select chosen class="form-contro ...

Is there a way to prevent the onClick function from being triggered during the rendering process?

Why is the function being called every time a React component is rendered, even though it shouldn't be? For example: const onClick = () => { console.log('hi'); } <button onClick={onClick}>CLICK</button> I am curious abo ...

A guide to designing a personalized filter for angular-moment

I am working on developing a unique Angular moment filter that displays the number of years passed since a specific birth date. For instance, if the value is 1990-06-05, the output should be 25. The code snippet I am currently using is: <time am-tim ...

The directive does not actively monitor changes to the value attribute

Whenever I click on an input field, a color picker pops up and the selected RGBA string is written back to the input's value attribute. Initially, I believed that adding ng-model="color" to the input tag would be enough for the color variable to hold ...

What is the best way to monitor the elements within ngRepeat in AngularJS?

Hello everyone, I am facing a minor issue that I seem unable to resolve. I have a search input field that allows users to search through a table in all columns. However, I am struggling to track the items in ngRepeat effectively. Below is the search inpu ...

Application utilizing electron technology featuring various tabbed browsing windows connecting to secure websites

Currently, I am in the process of developing my own unique version of a platform similar to using Electron technology. The objective for this app is to provide users with the ability to view multiple URLs simultaneously, such as and , through a tabbed i ...

Prevent editing in Angular UI-Grid while in view mode

Is there a method to enable or disable cell editing in the grid? For instance, I have a master-detail form screen where all controls are disabled using ng-disabled when a user wants to analyze a record. However, I am unable to prevent editing the grid. I ...

Error encountered: Denied access in AWS Transcription Node JS API

I have been working with the AWS transcription API in Node JS and my code looks like this: const tClient = new TranscribeClient({ region: "us-east-1", credentials: { accessKeyId: AWS_ID, secretAccessKey: SECRET, ...

Developing desktop applications using C# scripting

I currently have a C# desktop program that is able to work with new C# plugins. My goal is to modify the existing C# application to allow for scripts to be used as plugins. These scripts could be in JavaScript, Windows Script Host (WSh), or any other form ...

Having trouble setting default value using formControl in a component shared across multiple forms

Currently, I am facing an issue with setting a default value in a custom dropdown by using formControlName. In order to attach formControls to a shared component, I am utilizing ControlValueAccessors in the shared component. This allows me to update the fo ...

A new module is unable to load Angular Material

Recently, I developed an Angular material module similar to a core module. import { NgModule} from '@angular import {MatCheckboxModule} from '@angular/material/checkbox'; @NgModule({ imports: [ MatCheckboxModule ], exports: [ ...

Using Servicenow as a replacement for $sp.getRecord() within a scoped application

When working in a scoped environment in ServiceNow, the global application's method of accessing the current record through $sp.getRecord() is not available. Is there an alternative method to access the current record in a scoped application? Below i ...

Which costs more, using an undefined ng-bind or both ng-bind and ng-show together?

Assuming that toShowVar is undefined, which of these options would be more costly? <span ng-bind="toShowVar" ng-show="toShowVar"></span> or <span ng-bind="toShowVar"></span> The latter option would clearly not display anything o ...

Tips on assigning a data-id attribute

After a click event, I am attempting to dynamically set the data-id and/or value of a span using my JavaScript file. <span id="test"></span> Here is an example of the JavaScript code: nextLink: function(event) { $('#test').val ...

Is it possible to send a ternary expression inside a component as a prop based on whether the condition is true or false?

Is it possible to include a ternary expression inside a component and pass it as a prop depending on whether the condition is true or false? <ExperienceList onUserToggle={this.onUserToggle} jobs={this.state.jobs[this.state.value]} { th ...

Struggling to compile TypeScript code

After updating TypeScript and NodeJS to the latest versions, I decided to test a simple TypeScript example by compiling it using both Node terminal and Windows 10 command line. Here is the code snippet I used: let greeting:string = "Hello!"; console.log(g ...