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

As you scroll, this smooth marquee effect gently shimmers with each movement

I've been trying out this code to create a scrolling marquee text, but the issue is that after 7000 milliseconds it starts to jitter, which doesn't make the text look good. Any suggestions on how I can fix this problem? Let me know! <script ...

What is the recommended sequence for adding AngularJS to the index page?

I am new to AngularJS and currently working on a project where I need to include multiple JavaScript files in my index.html page. After doing some research, I came across a post on Stack Overflow that mentioned the importance of including the angular.js fi ...

Having trouble retrieving documents on a Windows 8.1 mobile device

For my app, I am utilizing Json files as a means of local storage. Interestingly, when using Visual Studio's emulator, reading and writing to the files function properly. However, upon connecting an actual device and attempting to run the app on it, I ...

Passing data retrieved from fetch requests in ReactJS using context: Best practices

Just started learning React and need some help. I'm trying to pass variables with json data to a component for further use but running into errors. What changes should I make to use variables with json data from Store.js in the product.js component? T ...

Do not reveal result of coin flip using Javascript and API

Even though I meticulously copied my professor's parsing process, the display isn't turning out as expected. It seems like something is off in my code. <div class="main"> <p>Heads or tails? click to toss the coin</p> & ...

Display array values in JavaScript from different arrays

I'm currently working on extracting data from my API to plot it in a graph. Specifically, I am interested in obtaining an array that contains only the 'date' values. Here's what I have managed to extract so far: https://i.sstatic.net/0 ...

The Unpredictable Behavior of Angular Routing

In the Angular 1 Application, I have set up the following route: .state('myConfiguration', { parent: '/', url: 'myConfiguration', resolve: { ready: function() { // eslint-disable-next-line no-undef retur ...

Tips on finding a JavaScript file using Google search

After releasing my jQuery plugin, I've noticed an increase in downloads. However, I'm curious to know where exactly it is being utilized. One idea I had was to search for the .js or .css file, potentially even looking at folder names. Is there a ...

Emotion, material-ui, and typescript may lead to excessively deep type instantiation that could potentially be infinite

I encountered an issue when styling a component imported from the Material-UI library using the styled API (@emotion/styled). Error:(19, 5) TS2589: Type instantiation is excessively deep and possibly infinite. Despite attempting to downgrade to typescript ...

What could be causing jQuery animate to malfunction on mobile devices when a viewport is present?

Everything seems to be working fine on my desktop webpage, but when I try it on mobile, there is no scroll... $("HTML, BODY").animate({ scrollTop: 500 }, 1000); This post suggests that mobile devices may not scroll on the body, but on the vi ...

What reasons might lead an object to be passed to a view as the exact term 'object' in Express.js?

Using nodejs, express, and ejs. I have a variable called 'result' which is properly defined. When I use console.log(result) within the router.get function on my index page, it outputs a correctly structured array of objects. After that, I rende ...

Issues with sending a POST request from a Swift front-end

Looking to integrate the Swift front end for uploading data to a Python Flask-powered PostgreSQL database. The current Swift code for sending a POST request within a View Controller is outlined below: func PostData(){ let parameters:[String: Any] ...

Leveraging Angular, ExpressJS, and NodeJS to enable users to download a text file by simply clicking a

My goal is to incorporate a download button that allows users to download a document from my node.js server. Behold the stylish download button: https://i.sstatic.net/s4CjS.png My tech stack includes Angular for the front-end and node.js along with exp ...

Is it possible to line up Ajax request in Javascript?

I am seeking a way to schedule an Ajax request to occur every second. The code I currently have in place functions flawlessly. window.onload = function () { setTimeout(doStuff, 1000); // Wait before continuing } function doStuff() { ...

"Exploring the power of AngularJS: Combining server side validation with dynamic client

Currently, I am trying to grasp the concept of declaring a form properly. My understanding is that one should simply declare the form in HTML and include ng-model directives like this: ng-model="item.name" When it comes to sending data to the server, I b ...

Executing Angular testing with the command $scope.$apply

What is the reason behind having to use $scope.$apply() in a test case for asynchronous processes to complete? Assume there is a service angular.service("a",function($q){ return { getValue: function(){ return $q.resolve(someObj) ...

ajax with names that are alike

I've set up a text input field that searches for file names on my server. However, it currently requires an exact match to display the file. I'm looking for a solution that can show me files even if the input text isn't an exact match. Here ...

What is the best approach in AngularJS for implementing a browser modal that returns a promise?

How can I implement a custom modal in my code that allows me to perform an action only after the user clicks 'okay'? var modalInstance = this.$modal.open({ templateUrl: '/app/tests/partials/markTest.html', controller: ['$sc ...

Maximizing the potential of views and subviews in AngularJS

I'm a newcomer to AngularJS and facing some challenges with implementing multiple views. Can someone provide guidance on how to achieve this? My goal is to create a file explorer with two columns: the left column displays subfolders and files, while ...

When iterating through it, a sorted array in Javascript mutates the window object, but not in any

I am working with Python Django to create a view that returns JSON data to a template. In this template, I initialize a global JavaScript variable like so: <script type="text/javascript"> coordinates = {{ coordinates | safe}} </script> Th ...