Strategies for refining the names in the dropdown options using AngularJS

I am working with a select element that has a name and id as options value. I am also adding '-' along with the name. However, there is a scenario where the name will be empty and in that case, the '-' should not be displayed.

The expected output should look something like this:

  1. name - 123
  2. 123

This is what I have attempted:

HTML:

<!doctype html>
<html ng-app="plunker" >
<head>
  <meta charset="utf-8">
  <title>AngularJS Plunker</title>
  <link rel="stylesheet" href="style.css">
  <script>document.write("<base href=\"" + document.location + "\" />");</script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.js"></script>
  <script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">  
    <select ng-model="model.selected" ng-options="item.Title as item.Title + '-' + item.ID for item in items"></select>
  <p>Selected: {{model.selected}}</p>  
</body>
</html>

Controller:

angular.module("app",[])
.controller("ctrl",function($scope){

  $scope.model = {
    selected : 'Chicago'
  }
    $scope.items = [
       {ID: '000.000.0001', Title: 'Chicago'},
       {ID: '000.000.0002', Title: 'New York'},
       {ID: '000.000.0003', Title: 'Washington'}
    ];  
});

Answer №1

When utilizing the if-else expression in your code, remember to use it in this format: OK? yes:no.

angular.module("app", [])
  .controller("ctrl", function($scope) {

    $scope.model = {
      selected: 'Chicago'
    }
    $scope.items = [{
        ID: '000.000.0001',
        Title: 'Chicago'
      },
      {
        ID: '000.000.0002',
        Title: 'New York'
      },
      {
        ID: '000.000.0003',
        Title: 'Washington'
      },
      {
        ID: '000.000.0004'
      }
    ];
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
  <select ng-model="model.selected" ng-options="item.Title as item.Title? (item.Title + '-' + item.ID) : ('' + item.ID) for item in items"></select>
  <p>Selected: {{model.selected}}</p>
</div>

Answer №2

Begin by ensuring that your controller and APP name are correctly set in the app.js file. Next, make the necessary changes to your code as shown below.

<select ng-model="model.selected" ng-options="item.Title as (item.Title !==''? item.Title + '-' : '') + item.ID for item in items"></select>

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

Effective strategies for managing form submissions with React and Typescript

As I dive into refactoring my code to TypeScript, especially as I am still getting accustomed to it, I find myself pondering about the HTML element types with React events. This has led me to rethink how I approach form creation and submission event handli ...

Experiencing issues with autoungrabify or autolock in cytoscape.js?

I have been working on a web application using Cytoscape.js, and I recently integrated the Edgehandles extension to allow users to add edges. The two types of edges that can be added are undirected and directed. Adding directed edges is functioning as expe ...

Execute JavaScript code prior to sending a Rails form

Before submitting the form, I would like to trigger the html5 geolocation javascript code. Here's how I envision the process: upon form submission, the user is prompted with a geolocation popup. After allowing access, the form data should be processed ...

Exploring the colors of legend navigation icons in Google Pie charts

Is there a way to customize the color of the navigation links in Google pie charts (specifically the blue text in the bottom right corner)? https://i.sstatic.net/Hk591.png ...

Hidden form in JavaScript does not submit upon clicking the text

My previous question was similar to this but with a smaller example. However, the issue with that code differs from my current code. (If you're curious, here's my previous question: JavaScript Text not submitting form) Currently working on my fi ...

Tips for managing the number of items returned in a dataProvider using AS3

*Hey there! I'm looking to only display 100 items in a list component from a dataProvider, even if it contains more than 500 or even 1000 items. Specifically, I want the first 100 items with cameras on to be included, and then fill the rest to reach a ...

Guiding a WordPress Form Submission to a Different Page

I'm currently using WordPress to create a form with the following code: [contact-form][contact-field label='What message would you like to send?' type='textarea' required='1'/]Word Limit: 50 words[contact-field label=&ap ...

A guide on accessing information from nested arrays in JavaScript

I am having trouble retrieving data from a JavaScript array as it keeps showing undefined. Here is the code snippet: sabhaDetailsArrayTemp.forEach(element => { let arra = []; console.log(element) //return tmp.m_category_name ; arra = this.onSa ...

React JS FormControl not functioning properly to toggle checkbox within a modal window

Upon editing a specific resource, a modal pops up to record the changes and update the application. Extracted from the homepage rfc const [flags,setFlags] = React.useState({}) . . . flags[object1]={flag1: true, flag2:false}; flags[object2]={flag1: true, f ...

Error: The array's property is not defined

I am currently working on a visualization tool for sorting algorithms, but I keep encountering an error that says "Cannot read properties of undefined (reading 'map')" in line let bars = this.state.array.map((value, index) =>. You can find my ...

AngularJS: Organizing elements across multiple ng-repeats

UPDATE: Here is a link to the plunker I created. In my JSON string, I have 2 parent objects with children. { "ParentA": { ... }, "ParentB": { ... } } Both ParentA and ParentB have children with some overlapping names. I ...

Iterate through an array containing objects that may have optional properties, ensuring to loop through the entire

I need help iterating through an array of objects with a specific interface structure: export interface Incident { ID: string; userName1?: string; userName2?: string; userPhoneNumber?: string; crashSeverity: number; crashTime: number; } Here ...

An issue arose while resolving symbol values statically. The function 'ɵmakeDecorator' cannot be called as function calls are not allowed in this context

I have developed a unique "Angular component library" that I refer to as ACL Now, I am incorporating this library into another project. Initially, when I execute ionic-app-scripts build, it completes successfully However, when I run ionic-app-scripts b ...

Providing an Angular Application using NginX

My Angular application has a specific structure that I usually deploy using an Express server. However, this time I need to deploy it with Nginx on a DigitalOcean instance. As someone new to Nginx, I'm unsure about how to set this up. Here is the init ...

Information is inaccessible beyond onBeforeMount in the Composition API of Vue 3

In my code snippet block, I have the following code: <script setup lang="ts"> import ApiService from '../service/api' import { reactive, onBeforeMount } from 'vue' let pokemons = reactive([]) onBeforeMount(async ()=> ...

Sharing parameters between functions in JavaScript

I have a working code but I want to modify the function getLocation to accept 2 arguments that will be passed to getDistanceFromLatLonInKm within the ajmo function. Currently, getDistanceFromLatLonInKm has hardcoded arguments and I would like to use variab ...

Tips for inserting the <a> HTML tag into a JSON array object

I am relatively new to creating array objects and I am unsure on how to add a link within a <a> tag in a JSON file. Here is the JSON object code: powerUpList: [ { id: 8, name: 'Automate your API column type ', description: & ...

I encountered the following error: Failed to parse due to the module '@babel/preset-react' being missing

Encountering a parsing error: Module '@babel/preset-react' cannot be found. Upon creating schema.js, tweetSchema.js, userSchema.js, issues arose with import, export, and export from all three files showing red lines. schema.js: import createSche ...

Strange glitches and slow loading problems plaguing website. (GoDaddy)

TackEmporium.com Lately, I have been revamping my website, which was originally given to me by a friend. I have been making slight adjustments to update its appearance while keeping its classic look with enhanced resolution and cleaned-up HTML5 code. Rec ...

`18n implementation in Node.js and front-end JavaScript for localization`

I am currently utilizing express js 4.0 and have set up the i18n module from https://github.com/mashpie/i18n-node in combination with ejs views. My goal is to extend this i18n functionality to .js files as well. Is there a way to enable the i18n function ...