How can I showcase a chosen name in a <p> tag using a Select dropdown, and then pass the selected ID to a controller in AngularJS

I am working with a select input in my HTML that is populated using ng-options. My goal is to display the selected NAME below, while sending the selected ID back to the controller. I am able to access the required id from ng-model="user.category". How can I achieve displaying the selected name along with showing the available options?

<select ng-model="user.category" ng-options="category.id as category.name for category in categories" class="form-control select" required>
  <option value="{{category.name}}">Select a Category</option>
</select>

<p>Selected Name : {{user.retailerBranchId}}</p>

Answer №1

<div ng-app="myApp">
  <select ng-model="user.choice" ng-options="option for option in choices" class="form-control" required>
    <option value="{{choice.name}}">Make a Selection</option>
  </select>

  <p>Chosen Option : {{user.choice.id}}</p>
</div>

Answer №2

By turning retailerBranchId into a method, you can utilize lodash's _.find() function (or even the native find method). Your user category gets updated based on your selection, which contains the necessary id for reference:

function getRetailerName() {
  return _.get(_.find(this.categories, { id: user.category }), 'name', '');
}

This method also handles failures gracefully; if no matching name or item is found based on the id, it will simply return an empty string.

Update: To implement this method, you would use it as follows:

<p>Available at: {{ user.getRetailerName() }}</p>

However, for optimal usage, consider using it in this manner:

<p data-ng-bind="'Available at: ' + user.getRetailerName()"></p>

Answer №3

Could you please attempt the following method?

Controller code to retrieve the selected Category Name:

$scope.getSelectedCategoryDetail=function(selectedCat){
   angular.forEach($scope.categories, function(cat){
      if(selectedCat===cat.id){
         $scope.user.name=cat.name;
      }
   });
};

Template with ng-change event included:

<select ng-model="user.category" ng-options="category.id as category.name for category in categories" class="form-control select" required>
  <option value="{{category.name}}" ng-change="getSelectedCategoryDetail(user.category)">Select a Category</option>
</select>


<p>Category Id : {{user.category}}</p>
<p>Category Name : {{user.name}}</p>

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

Transform variable names from Java and AngularJS conventions to standard English

In my quest, I have successfully used JAVA Reflections to extract attribute names from a class. However, I desire to change the variable naming convention, such as transforming firstName into First Name. I currently contemplate utilizing the .split() meth ...

Avoid causing the newline character to display

var i = 'Hello \n World' console.log(i) /* Output: Hello World */ /* Desired output: Hello \n world */ var j = 'javscr\u0012ipt' console.log(j) /* Output: javscr ipt */ /* Desired output: javscr\u0012ipt */ ...

Angular $resource encounters a 400 Bad Request error when attempting a PUT request, triggering the $resolve and $promise

My service is structured as follows (with variables removed): angular .module('app') .factory('Employee', function($resource) { return $resource("https://api.mongolab.com/api/1/databases/:dbName/collections/:collectionN ...

Loading large amounts of data efficiently with Angular and Firebase

Currently, I am utilizing AngularJS in conjunction with Firebase. Objective: My aim is to showcase all the information stored within my Firebase database (which consists of a fixed number of approximately 1600 items). Challenge: The issue at hand is that ...

Passing a message from a directive in AngularJS using event broadcasting

Many developers are incorporating the following code snippet into their projects: $rootScope.$broadcast('someEvent', someParameter); Later, in a specific controller: $rootScope.$on('someEvent', function(event, e){ /* code implementat ...

Error: Trying to access properties of an undefined object (specifically 'promise.data.map')

Currently, I am in the process of writing unit tests for a project built with Angular version 1.2. For my controller tests, I have set up a mockService that returns a deferred promise. One of the service methods looks like this: function getItems() { ...

What is the best way to toggle the visibility of a side navigation panel using AngularJS?

For my project, I utilized ng-include to insert HTML content. Within the included HTML, there is a side navigation panel that I only want to display in one specific HTML file and not in another. How can I achieve this? This is what I included: <div ng ...

Issues with Ionic Toggle displaying incorrect value

I created a basic test using an ionic toggle, but I'm encountering an issue where my alert returns False when the toggle is set to True and True when it's set to false. Any suggestions on how to fix this? http://codepen.io/anon/pen/jtKCf $scope ...

Ways to adjust image placement and size post-rotation with CSS/JS to ensure it stays within the containing div and avoids being cut off

Check out this jsfiddle I've been experimenting with. The jsfiddle is designed to rotate an image by 90 degrees in either clockwise or anti-clockwise direction upon button click. However, the rotated image currently appears outside of its parent div. ...

Utilize Django's TemplateView in ModelAdmin's add_view for seamless integration

As per the Django Admin site documentation, I have discovered that I can customize ModelAdmin.add_view to inject a custom view. My intention is to include a TemplateView to modify an admin page for adding or changing models. This unique view will feature ...

The Challenge of Upgrading from AngularJS 1 to Angular 2: An Adapter Solution

<html lang="en"> <head> <meta charset="utf-8" /> <link rel="stylesheet" href="app.css" type="text/css" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.5/angular.js"></script> <script src="https:/ ...

Angularjs is encountering an issue because there is no 'Access-Control-Allow-Origin' header on the requested resource

Encountering an Issue: Getting the following error message: Failed to load http://localhost:10948/Api/Home/PostData/[object%20Object]: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost: ...

In Chrome version 69.0.3497.100, material design does not display dynamic elements off the screen

STACK: react: 16.8.6 redux: 4.0.1 DESCRIPTION: When using $compile to dynamically add elements on a page, I encountered an issue in Firefox (76.0) where input elements that are out of the screen are not rendered. Only the labels are displayed. view image ...

Local variables in AngularJS across multiple Angular applications

Looking for a method to retain a local variable not affected by path or angular app changes. Attempted using $window.localStorage.set and get item, rootScope, and $window.variable with no success. ...

AngularJS ui-select not responding correctly to selected items

Currently, I am utilizing the ui-select module within AngularJS. <ui-select ng-model="tipData.category" search-enabled="false" name="category" required="required" class="orange-site-color-select custom-select"> <ui-select-match><span clas ...

Can someone clarify the distinction between returning a value directly or using Promise.resolve within the then() function?

What is the distinction between: new Promise(function(res, rej) { res("first example"); }) .then(function(result) { return "bbb"; // directly returning string }) .then(function(result) { console.log(result); }); and this: n ...

angular setting the scroll offset in ng-infinite scroll

Looking for a way to maintain my offset value in order to fetch the next set of data whenever I scroll or click on 'Load more'. This is essential for enhancing performance. Currently, I am experimenting with setting an offset and limit, passing t ...

Struggling to send information using Angular $resource?

I've been working on sending data to an API using Angular's $resource. Currently, I can successfully retrieve data from my test server using a GET request or querying. However, I'm having trouble figuring out how to send new data to the serv ...

"Crafting a Personalized TabControl Directive in AngularJS: Step-By-

Currently, I am using Zurb Foundation 4 as my CSS/Grid Framework which includes a Tab Control feature. However, when this tab control is placed on a page loaded via ng-view, it malfunctions. To address this issue, I decided to create my own directive sinc ...

Saving resources with a promise in Angular

I am facing a challenge while trying to handle a promise from the angular $resource save function. According to the documentation, I should be able to access the raw $http promise by using the $promise property on the returned object. Here is an example: ...