how to assign values to objects in angularjs select box

Here is my Angular code:

angular.module("myApp",[])
.controller("myCtrl",function($scope){
  $scope.projectObj = {"proId":"33","proName":"samal"}
  $scope.projectArr = [{"proName":"samal","proId":"33"},{"proName":"aaa","proId":"47"},{"proName":"sdf","proId":"48"},{"proName":"sdf","proId":"49"},{"proName":"sddd","proId":"50"},{"proName":"dddd","proId":"51"},{"proName":"ttt","proId":"52"},{"proName":"sdf","proId":"53"},{"proName":"sdf","proId":"54"},{"proName":"sdf","proId":"55"},{"proName":"sdf","proId":"56"},{"proName":"sdf","proId":"57"},{"proName":"sdf","proId":"58"},{"proName":"sdf","proId":"59"},{"proName":"sdf","proId":"60"}]
})

Next, I have a select box:

<select ng-model="projectObj">
   <option value="{{item}}" ng-repeat="item in projectArr">{{item.proName}}</option>
</select>

I already have $scope.projectObj assigned with an object and it is already inside $scope.projectArr. My goal is to pre-select the proName when loading the HTML file. How can I achieve this? Here is the link to my example on Plunker.

Answer №1

It's not recommended to repeat options in order to display a select dropdown. Instead, I recommend using the ng-options directive for object binding with ng-model

<select  flex ng-model="projectObj" 
  ng-options="item as item.proName for item in projectArr">
</select> 

Then, assign projectObj from projectArr.

$scope.projectObj  = $scope.projectArr[0];

Check out the demo here


For Angular material, use md-select like below and include

ng-model-options="{trackBy: '$value.proId'
to preselect the object directly. Remember to follow the Dot Rule when defining ng-model

Markup

<md-input-container>
  <md-select ng-model="projectObj" placeholder="Select a state"
    ng-model-options="{trackBy: '$value.proId'}">
    <md-option ng-value="item" ng-repeat="item in projectArr">
      {{ item.proName }}
    </md-option>
  </md-select>
</md-input-container>

View on CodePen

Answer №2

Implementing ng-selected can be a handy solution for the situation at hand.

<option value="{{element}}" ng-selected="element" ng-repeat="element in projectArr">{{element.proName}}</option>

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

Encountering a non-constructor error while trying to import packages in React Typescript

I am currently working on a project that utilizes React with Typescript. While attempting to import a package, I encountered an error stating that the package lacks a constructor when I run the file. This issue seems to be prevalent in various packages, a ...

Retrieve the specific key or object number by conducting a search in JavaScript

I am faced with the challenge of editing a large XML file by searching for a specific keyword within the "event name" field and changing the corresponding "active" value to either 1 or 0. The structure of the data file is as follows. I have managed to modi ...

The .get function is functioning properly during development, but encountering issues in the production environment

Here is the scenario: while running my server on node.js locally, the client code successfully retrieves data from the server. However, upon pushing the code to the live server, the client receives a /getSettings 500 (Internal Server Error). The main index ...

What is the best way to create a Div element that functions as a button, becoming active when clicked while deactivating all other Div elements

function toggleButton1() { $("#button1").toggleClass("button-active button-inactive"); $("#button2").toggleClass("button-inactive button-active"); $("#button3").toggleClass("button-inactive button-active"); } function toggleButton2() { $("#butto ...

Sorting functionality in Dyntable is not functioning properly when called from an Ajax request

I can't seem to get DynaTable with Ajax to work properly. Sorting, searching, and pagination are not functioning as expected. When I click on the column header, nothing changes in my table. Could someone please assist me? Below is my code snippet: H ...

Is it possible for a JavaScript .execute function to be executed synchronously, or can it be transformed into an Ajax

Currently, I am utilizing the ArcGIS API for Javascript which can be found at this URL: The JavaScript code snippet I'm working with appears to be running asynchronously. Is there a way to convert it to run synchronously or potentially transform it i ...

When using Node.js with Nginx, requests are timing out at the Nginx level before the processing is completed in Node.js

I have a setup where I use Nginx and Node.js servers. The process involves uploading a file from a browser to Nginx, which then forwards it to Node.js for processing. However, I've encountered an issue when dealing with large files - the upload crashe ...

Example of Node-gallery used in isolation, displaying an error event with the message "ENOENT"

I am currently experiencing an issue with the node-gallery npm module. After installing dependencies inside the /example directory, I attempted to run the app. The result was a localhost:3000/gallery page, but upon the page fully loading, I encountered the ...

"Efficiently sharing information in a multi-tenant application: strategies for seamless data transfer between front

In my development of a multi tenancy application using Node.js/Mongoose and React, I made the decision to utilize a single database for all users. The main collection, dubbed companies, serves as storage for basic company data and includes a unique compan ...

AngularJs - utilizing two-way binding within an ng-repeat using a view model concept

I am working on a project where I have multiple checkboxes displayed using ng-repeat in the following manner: <tr data-ng-repeat="item in blogCategory.items track by $index"> .... <td> <label class="toggle"> <input ...

Calculate the total of all values associated with a dynamically generated key within an array of objects

I'm trying to calculate the sum of similar keys in an array of objects. Each object in the array will have some common keys, but not all arrays will share the same set of keys. I'm considering storing these keys in a separate array and then loopi ...

Is there a way for me to display the output within the component rather than using console log?

I created a simple app.js file in React that continuously checks if a number is prime or not and logs the result in the console every second. Now, I am looking to display this information on my homepage instead of in the console. Any suggestions on how I ...

Having difficulty transmitting a base64 video via Ajax Post to PHP

While attempting to upload a MP4 video with a size of 16.9 MB via ajax asynchronous post to a PHP file, an error is displayed in the console: POST net::ERR_EMPTY_RESPONSE It seems that the issue is related to the PHP memory_limit setting. When set to 200 ...

What is causing my console to be spammed by Web3 .GetReserves()?

My code is successfully retrieving the data, but I am encountering an issue where my request for token reserves ends up spamming the server with repeated requests. This causes me to temporarily lose access to data retrieval (I hope I'm not the only on ...

Guidance on navigating a JSON object containing an array with backslashes using Jquery or Javascript after receiving it from an AJAX request

I am facing a challenge with looping through an array inside JSON data to display it in a table based on nationalities. The issue arises from the presence of backslashes in the array data, making it difficult to iterate through. This data is fetched using ...

React Native app utilizing Expo can successfully import local databases in a web view, but encounters issues when attempting to do so on smartphones

I created a small learning app and imported data from a local database using the following code: import { StatusBar } from 'expo-status-bar'; import { Platform, FlatList, StyleSheet, Text, View, TextInput, Button, SafeAreaView, ScrollView } from ...

Node.js: Module not found error

When I run the command below to install a module from the NPM registry: npm install dc All files are successfully installed, but upon running the script dc, it fails to resolve a dependency. $ node web-test.js module.js:340 throw err; ^ Error: ...

Is the entire web page generated on the server with each request using getServerSideProps()?

As I understand it, getServerSideProps will dynamically generate the complete page on every request, rather than pre-building it. But does getServerSideProps always generate the entire page upon each server request, or only when the data in the database ha ...

What are the reasons behind the issues encountered when enabling "Optimization" feature in Angular that affect the proper rendering of PrimeNg elements?

Angular Version : 9.x Primeng Version : 9.x We've encountered an issue with PrimeNg elements not rendering correctly in our dev/prod environments, although they work fine in the local environment. After some investigation, we found that the culprit ...

Check domains using Jquery, AJAX, and PHP

I'm currently developing a tool to check domain availability. Here is the PHP code I have so far: <?php $domain = $_GET["domname"]; function get_data($url) { $ch = curl_init(); $timeout = 5; curl_setopt($ch, CURLOPT_URL, $url); ...