Populate an AngularJS select dropdown with JSON data and automatically pre-select the specified value

I am currently dealing with 2 entities: project and project_types. Each project can have one or multiple project_types associated with it.

Using ajax (ng-init), I am retrieving the project data (including its related project_types) and all available project_types for selection:

$scope.showProject = function() {
        $http.post($scope.apiUrl+'/show', {
            projectslug: $attrs.projectslug
        }).success(function(data, status, headers, config) {
            $scope.project = data;
        });

        $http.post($scope.apiProjectTypesUrl+'/index', {
        }).success(function(data, status, headers, config) {
            $scope.project_types = data;
        });
    };

The {{project}} scope contains the following JSON:

{"id":1,"slug":"test","active":1,"name":"Test","description":"dgdgdgdg","from":"2015-12-22 00:00:00","to":"2015-12-22 00:00:00","created_by":1,"updated_by":1,"created_at":"2015-12-22 12:08:47","updated_at":"2015-12-22 12:08:47","deleted_at":null,"from_date_time":"22.12.2015","to_date_time":"22.12.2015","formatted_description":"dgdgdgdg","users":[],"project_types":[{"id":4,"slug":"event","active":1,"name":"Event","description":"","created_by":0,"updated_by":0,"created_at":"2015-12-22 09:49:43","updated_at":"2015-12-22 09:49:43","deleted_at":null,"pivot":{"project_id":1,"project_type_id":4,"created_at":"2015-12-22 13:13:12","updated_at":"2015-12-22 13:13:12"}}]}

And in the {{project_types}} scope, there is this JSON:

[{"id":4,"slug":"event","active":1,"name":"Event","description":"","created_by":0,"updated_by":0,"created_at":"2015-12-22 09:49:43","updated_at":"2015-12-22 09:49:43","deleted_at":null},{"id":5,"slug":"sfsfsfsfsfsfsfsfsfsf","active":1,"name":"sfsfsfsfsfsfsfsfsfsf","description":"","created_by":0,"updated_by":0,"created_at":"2015-12-22 09:50:23","updated_at":"2015-12-22 09:50:23","deleted_at":null},{"id":6,"slug":"eteett","active":1,"name":"eteett","description":"","created_by":0,"updated_by":0,"created_at":"2015-12-22 10:07:55","updated_at":"2015-12-22 10:07:55","deleted_at":null},{"id":7,"slug":"sfssfsf","active":1,"name":"sfssfsf","description":"","created_by":0,"updated_by":0,"created_at":"2015-12-22 12:36:37","updated_at":"2015-12-22 12:36:37","deleted_at":null}]

In my HTML code, I am creating a select field (multiple):

<select id="projectTypes"
   class="form-control"
   name="projectTypes[]"
   ng-model="project.project_types"
   ng-options="project_type.id as project_type.name for project_type in project_types"
   multiple="multiple">
</select>

There are 4 options in the select field, which match the entries in the project_types JSON.

However, I am facing difficulty selecting the appropriate relations from the project in the select field. The ng-model="project.project_types" consists of the following JSON:

[{"id":4,"slug":"event","active":1,"name":"Event","description":"","created_by":0,"updated_by":0,"created_at":"2015-12-22 09:49:43","updated_at":"2015-12-22 09:49:43","deleted_at":null,"pivot":{"project_id":1,"project_type_id":4,"created_at":"2015-12-22 13:13:12","updated_at":"2015-12-22 13:13:12"}}]

I have been struggling to make this work properly. No value is being default-selected in my select field.

Thank you for guiding me in the right direction!

Answer №1

Did you consider using the "track by" option?

 ng-options="fruit.id as fruit.name for fruit in fruits track by fruit.id"

Providing a functional code snippet or fiddle would make it simpler to offer assistance.

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

What is the best way to transfer information between two components in React.js by simply clicking a button?

One of the challenges I am currently facing involves rendering data from the Pokemon API in a table. Within this table, there is a button that allows users to select specific data when pressed. My goal is to send this selected data from the table component ...

Switching from React version 15.6.2 to 16 results in disruptions to the functionality of the web

Currently, I am encountering an issue where none of my index.js files are rendering. After using the react-scripts to build my web application in version 16.2.0, I receive an error stating that r.PropTypes is undefined when trying to access the localhost a ...

What is the method for including an item in a Dictionary?

I encountered an issue with a nested dictionary in a Json file. Here is the current content of the file (highscore_history.txt): { "Highscores": { "0highscore": 2 } } My goal is to add a new entry into the nested dictio ...

Customize the theme of Ant Design for VueJS

I have successfully set up my Vue3 application with Tailwind and Ant Design. However, I am facing issues with customizing the Ant Design theme. I have been referring to this guide. When trying to customize the theme, I encountered the following error: Err ...

The unexpected blank space appearing beneath my website as a result of images and videos placed on the

There seems to be some random white space on my website between the main body elements and the footer. Interestingly, removing the cat image and videoplayer eliminates this white space. However, I don't want to remove them completely, so I'm tryi ...

Implementing Mean Stack with Express to Serve AngularJS Static Resources

Having created apps using Node and Angular separately, I am now facing a challenge in combining the two. I am unsure how to send all the views to the front end when index.html is sent. Here is the code snippet from my server: ... app.use(express.static(&a ...

What is the best method to obtain the following id for an image?

Whenever I hover over the li with the number 3, I am getting the wrong number for the next id in the img tag. The first time, I get next id = 4 which is incorrect. But on the second hover, I get next id = 0 which is what I actually need. How can I correctl ...

Creating a JSON string in the Java programming language

Working with JSON while developing an Android SDK can be a bit frustrating. Here's an example: post_my_server("{\"cmd\":\"new_comment\"}"); The process of manually escaping quotes can be tedious. Is there a more efficient way to ...

Having trouble integrating Animate.css with AngularJS version 1.3

As per multiple online sources, this method is said to be effective. <li ng-animate="{enter: 'animated shake'}" ng-repeat="name in names | filter:search"> <a href="#"> {{name}} </a> </li> You can view the Plunkr exampl ...

Is there a way to delay loading 'div' until a few seconds after the 'body' has been fully loaded?

Is there a way to delay the appearance of the "text-container" div after the image is displayed? I have attempted to achieve this using JavaScript with the following code: <script> window.onload = function(){ var timer = setTimeout("showText()",700 ...

Leveraging JSON in conjunction with AJAX and Python database operations

I am a beginner in Python and I am attempting to access the database through Python in order to retrieve results in a JSON array using AJAX. When I test it by returning a JSON list and triggering an alert in JavaScript, everything works fine. However, as ...

Choose the tag and class then retrieve the custom attribute

I'm currently attempting to retrieve a specialized attribute utilizing jquery and subsequently choose it, nevertheless I am encountering some difficulties with the process Below is the jquery code I have implemented to access the value var stockId = ...

Enhance your JavaScript code by using the powerful Node.js util.format() method

I have been attempting to enhance the functionality of the node.js util.format function by allowing it to be used as a prototype (for example: "Hello %s".format("World")). Unfortunately, my attempts have all failed. I've tried different formats like: ...

How can one efficiently navigate through extensive functions without risking surpassing the stack limit?

I am currently developing an application in Node.js that requires numerous configuration and database calls to process user data. The problem I am facing is that after reaching 11,800+ function calls, Node throws a RangeError and exits the process. The er ...

Looping through items with ng-repeat and creating a submenu with M

When constructing a menu from a JSON file with submenus using the JQuery.mmenu plugin, I encountered an issue when trying to implement the submenu structure with ng-repeat. The raw HTML approach worked perfectly, but as soon as I introduced ng-repeat to dy ...

Troubleshooting jsPDF problem with multi-page content in React and HTML: Converting HTML to PDF

I need to convert HTML content in my React application into a PDF file. My current approach involves taking an HTML container and executing the following code snippet: await htmlToImage .toPng(node) .then((dataUrl) => { ...

Steps for displaying a loading image during the rendering of a drop-down list (but not during data loading):

Using jQuery's autocomplete combobox with a large dataset of around 1,000 items. The data loads smoothly from the server, but there is a delay when expanding the drop-down list to render on screen. Is there a way to capture the initial click event on ...

Defining JSON Schema for an array containing tuples

Any assistance is greatly appreciated. I'm a newcomer to JSON and JSON schema. I attempted to create a JSON schema for an array of tuples but it's not validating multiple records like a loop for all similar types of tuples. Below is a JSON sampl ...

Uncovering the hidden gems within a data attribute

Trying my best to explain this clearly. What I have is a data-attribute that holds a large amount of data. In this case, I need to extract each individual basket product ID and display them as separate strings. The challenging part for me is locating thi ...

What is the most efficient and hygienic method for storing text content in JavaScript/DOM?

Typically, I encounter version 1 in most cases. However, some of the open source projects I am involved with utilize version 2, and I have also utilized version 3 previously. Does anyone have a more sophisticated solution that is possibly more scalable? V ...