Setting a default value for a select element in AngularJS can be accomplished by using the

Here is the code snippet I am working with:

  <select class=" text-center form-control" name="custname"
            ng-model="a.custid" 
            ng-init="devcustname[0].customer_name"
            ng-change="fetchassocd(a)">

     <option value="" selected="true">Please select a Customer name</option>
     <option ng-repeat="a in devcustname | orderBy:['customer_name']"
            value="{{a.customer_id}}">{{a.customer_name}}
    </option>
  </select>

I am trying to set the default value as devcustname[0].customer_name. However, the ng-init directive seems to be causing some issues. Ideally, when devcustname[0].customer_name is null or undefined, I would like the "Please select a Customer name" option to be displayed as default.

The challenge I am facing is that if I switch to using ng-options, I lose the ability to display the "Please select a Customer name" message.

Answer №1

angular.module('app', []).controller('ctrl', function($scope){
   $scope.customerList = [
    {customer_id: "3", customer_name: '', customer_email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="197f786a597e74787075377a7674">[email protected]</a>", contact_no: "23", address_line1: "6, f4"},
    {customer_id: "4", customer_name: "ab", customer_email: "sm", contact_no: "12", address_line1: "R V Road, 10th cross"},
    {customer_id: "5", customer_name: "da", customer_email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="47742607202a262e2b6924282a">[email protected]</a>", contact_no: "33", address_line1: "6, f4"}
  ];   
  $scope.selectedCustomer = {custid: "4"};
})
<script src="//code.angularjs.org/snapshot/angular.min.js"></script>

<div ng-app='app' ng-controller='ctrl'>
  <select class="text-center form-control" name="custname" ng-model="selectedCustomer.custid" ng-init="defaultName = customerList[0].customer_name || (selectedCustomer = {custid:''})" ng-change="fetchAssociatedData(selectedCustomer)">
    <option value="" ng-disabled="isDisabled">
    -Please select a Customer name-
    </option>
    <option ng-repeat="customer in customerList | orderBy : 'customer_name'" value="{{customer.customer_id}}">
      {{customer.customer_name}}
    </option>
 </select>  
</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 can I retrieve the checked values of checkboxes and store them in an array using React?

https://i.sstatic.net/jTRRU.png This toggle button is dynamically generated based on data, and I need to save the checked values in an array. Code {this.state.customersmsselect.map((e, key) => { if(e.isactive == "ON"){ return ( &l ...

Tips on retrieving complete information from mongoose when the schema contains a reference

I have a schema that includes [content, name, email], and I need to retrieve all three data fields and render them on the frontend simultaneously. Can you provide an example of JavaScript code that accomplishes this? const UserSchema = new mongoose.Schem ...

Utilizing the NestJS Reflector within a Custom Decorator: A Comprehensive Guide

I have implemented a solution where I use @SetMetaData('version', 'v2') to specify the version for an HTTP method in a controller. Additionally, I created a custom @Get() decorator that appends the version as a suffix to the controller ...

Navigating to a different page using the browser address bar causes the context to be reset

Upon receiving the user's data from the API on the login page, it is set in the user context. Subsequently, upon redirection to the AdminPanelApp, the data within the user context is displayed accurately. However, if I am in the AdminPanelApp and navi ...

Async JavaScript generator-style programming

It seems that the future trend in writing asynchronous JavaScript code is shifting towards using generators instead of callbacks, particularly in the V8/Node.js community. While this may be up for debate, it's not the main focus of my inquiry here. I ...

Observing a class getter within Vue.js

The issue at hand I am facing a challenge in ensuring my page automatically updates when new data is available. I am using Ionic, and have a page that displays all the items collected by the user in a visually appealing manner using an ion-grid. To achiev ...

Clearing out content from owlCarousel: A step-by-step guide

I have a model where I am displaying a couple of images in an owlCarousel div. The issue arises when I close the model and open it again, the new set of images get appended to the previous ones. I want to clear all items from the previous model and reini ...

A pair of buttons each displaying a unique div block

I am facing an issue with my jQuery script. I want to be able to click on one of the previewed text associated with a button and then have the other one close automatically. The desired effect is for the text to slide down using slideDown() and disappear ...

What is the best way to retrieve data from the past day using moment.js or the date function

I have data stored in my database that I need to query for entries from yesterday. However, when I try the following code: momentendYest', moment().startOf('day').subtract(1,'day').toDate() it returns today's date at 7am inst ...

Is it possible for a Vue.js build to encounter errors due to unregistered components?

Exploring a component template... <template> <Unknown></Unknown> </template> In the context of this template, Unknown could be either a globally registered component or not. Upon encountering this scenario at runtime, an informa ...

PHP code for determining the monthly subscription package cost

I have recently launched an e-commerce website that offers lunch and dinner delivery services. I am reaching out for help as I have encountered a problem with calculating prices based on different packages/plans available on the website. 1. Weekly 2. Mo ...

Obtaining rotate3d values using JavaScript / jQuery

When dealing with an element that has a transformation like the following: style="transform: rotate3d(1, 0, 0, -50deg);" I am looking to extract the value -50 using Javascript or jQuery. It's essential for me to get the absolute value, so negative d ...

Connecting RxJs to a React component: a step-by-step guide

Many examples demonstrating how to observe button clicks using RxJS typically follow this pattern: var button = document.querySelector('button'); Rx.Observable.fromEvent(button, 'click') .subscribe(() => console.log('Clicked! ...

Creating a never-ending loop with Vue.js and JavaScript in an asynchronous function

My current approach involves using an async function to interpolate specific elements from the DOM, and while it is effective, I am unable to pass the lint verification. This has led me to seek out alternative solutions. Below is my existing code: async ...

Adding Rows to a DataTables Table

I am currently working on dynamically adding <tr/> tags to a DataTable, but I am struggling to find detailed documentation on how the process of "adding TR" is meant to be executed. Below is the setup of my DataTable: $("#Grid").DataTable({ state ...

Getting PHP Data from AngularJS: A Step-by-Step Guide

I have successfully sent FormData from AngularJS to PHP, but I am struggling to figure out how to get the $base64 variable back into my AngularJS code. The documentation provided by AngularJS hasn't been very helpful in this regard. https://docs.angu ...

The fade toggle method in the List class for the specified element at the given index is experiencing issues with adjusting

I am dealing with 2 sets of items that have different classes var listEditCommitLinks = document.getElementsByClassName('edit-comment-link'); var listEditCommitWrappers = document.getElementsByClassName('edit-commit-wrapper'); These a ...

"Exploring Firebase features, what is the process for generating a query using UID as a reference point

I recently developed a function that assigns a UID to the database along with an item's state: changestate(item) { var postData = { state: "listed", }; var user = firebase.auth().currentUser; var uid = user.uid; var updat ...

What is causing the issue in retrieving the JSON response from Django using the JavaScript Fetch API?

I am inexperienced with JavaScript. Currently, I am working on a project that involves using Django in the backend. In this project, my Django views function will generate a JSON response that my JavaScript fetch will retrieve. Below is the Django views fu ...

Tips for generating an about:blank webpage featuring a personalized iframe

I'm attempting to create a form with the following functionality: Enter a URL into a text box. Click a button and it opens an about:blank page in a new tab. The opened page contains an iframe that occupies the entire screen, with the src attribute se ...