Angular, choose, establish a default option

Despite my attempts, I am struggling to set the default option for a select element using AngularJS.

My Technologies: AngularJS, Angular-UI-router, Bootstrap

Key HTML snippet:

<select ng-model="selectedCompany" ng-options="c.name for c in companies" class="form-control"></select>

Juice Service Details:

vapelog.factory('Juices', function($http, $q){
    var Juices = {
        get : function() {
            var promise = $http.get('/juices').then(function(data){
                return data.data;
            });

            return promise;
        },
        show : function(id) {
            var deferred = $q.defer();

            $http.get('/juices/'+id).then( function ( juice ) {
                $http.get('/companies').then( function ( companies ) {

                    juice.companies = companies;
                    deferred.resolve( juice );

                }, function getAcctError() { deferred.reject(); });
            }, function getUserError() { deferred.reject(); });

            return deferred.promise;
        },
    }

    return Juices;
});

Controller Setup:

vapelog.controller('JuiceDetailCtrl', ['$scope','$stateParams','Juices',function($scope, $stateParams, Juices) {
    var id = $stateParams.juice;
    $scope.juice = {};
    $scope.selectedCompany = {};

    Juices.show(id).then(function(juice){
        $scope.juice = juice.data;
        $scope.companies = juice.companies.data;
        $scope.reviews = $scope.juice.reviews;
        $scope.selectedCompany = $scope.juice.company;
    }, function(){
        console.log('error');
    });

    $scope.tfIcon = function(item){
        if(item == "1"){
            return 'glyphicon-ok';
        } else {
            return 'glyphicon-remove';
        }
    }
}]);

While the select box displays all items correctly, it fails to pre-select an option. Instead, it starts with a blank value.

The presence of $scope.companies leads me to believe that the $http.get() call has been successful and $scope.selectedCompany should also be populated. However, this is not the case. Any insights on where I might be going wrong would be appreciated.

Answer №1

When working with the $scope.juice.company object in JavaScript, it is essential to note that this object is not directly included in the array of companies. You will need to manually search for the corresponding company within the companies array. One approach is to use a property such as id to identify the correct company:

$scope.selectedCompany = findCompany($scope.juice.company, $scope.companies);

function findCompany(theCompany, companies){
    var result;
    angular.forEach(companies, function(companyInArray){
         if(companyInArray.id === theCompany.id){
             result = companyInArray;
         }    
    });

    return result;
}

Answer №2

If you assign the ID as the model in the select element, you can then define it in the controller:

app.controller('Ctrl', function ($scope) {

    var selectedJuice;

    $scope.juices = [];
    $scope.juice = 2;


    $scope.juices.push({"id": 1, "fruit": "orange"});
    $scope.juices.push({"id": 2, "fruit": "apple"});
    $scope.juices.push({"id": 3, "fruit": "pear"});
    $scope.juices.push({"id": 4, "fruit": "pineapple"});

});

HTML:

{{ juice }}
<select ng-model="juice" ng-options="juice.id as juice.fruit for juice in juices"></select>

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

Using JQuery to create a button inside a Modal dialog box

My goal is to select a row within a Table that is located inside a Modal window, and then have a button ('newBtn') within that Modal window trigger a post request to the server with the selected id of the row. However, the issue I am encountering ...

Tips for creating a custom axios response depending on the error code returned by the response

I am currently working on implementing a global error handling system in my Vue application. Within my project, I have an api.service.js file that contains the necessary code for Axios setup and various HTTP request functions such as get and post: /** * S ...

jQuery: use the "data-target" attribute to toggle the display of a single content area

My code generally works, but there is an issue. When clicking on "Link 1" followed by "Link 2", only the content for Link 2 should be visible. How can I achieve this with my code? $("li").click(function() { $($(this).data("target")).toggle(); // ...

Issue with border spacing functionality

I'm having some difficulty with my border spacing in CSS. No matter what size I specify, it doesn't seem to have any effect. I just want to use a border for the top line. Here is my CSS: p { border-spacing: 5000px; text-align: right; ...

Removing an item from an ng-repeat loop while also dealing with a FormController within

I am encountering a significant issue with form inputs nested within the ng-repeat directive. I require an input that is an array and can vary in size; allowing users to add or remove parts of the form. Within the ng-repeat directive, there is an ng-form ...

Is the Ajax response value consistently 1?

I am facing an issue where a JavaScript in an HTML page is sending two variables to a PHP script, which then echoes one of the variables at the end. However, the response value always remains 1. Despite trying methods like alerting, console.log, and puttin ...

Is it possible to create a dynamic template in Angular using external sources?

My goal is to dynamically load HTML content using AJAX and then compile it, as it contains Angular directives. I have a specific class that includes methods for utilizing Angular outside the scope of an angular controller or directive: var AngularHelper ...

Mongoose Alert Utility Directive

const mongoose = require('mongoose'); module.exports = { init: () => { const dbOptions = { useNewUrlParser: true, useUnifiedTopology: true, autoIndex: false, reconnectTries: Number.MA ...

Error encountered: unable to locate module - '@deck.gl/exper-layers'

When attempting to run npm start on the trip example in deck.gl, I encountered an issue. Although other examples open without any problems, the trip example is giving me this npm error: Module not found: Error: Can't resolve '@deck.gl/experim ...

"Automatically set the default value in a drop-down menu depending on specified

Conundrums arise as shown in this dropdown issue with default selection. Provided below is the JSON utilized to populate the dropdown. { "key": "all", "value": "First", "default":"N" }, { ...

I have successfully converted an SQL Join query into JSON, but now I am unsure of how to interact with the

I recently ran an SQL Join on two tables and obtained the following results: _____People_____ name: "Jane" age: 35 job_id: 1 _____Professions_____ job_id: 1 title: "Teacher" "SELECT * FROM People INNER JOIN Professions ON People.job_id = Professions.job ...

The Express middleware type cannot be assigned as expected

I'm encountering an error where my first middleware is being red underlined. I can't figure out why it's only happening to the first one. Can anyone provide some guidance on this issue? I'm still quite new to TypeScript. Did I overloo ...

Displaying the overall count for a bar chart within the tooltip title of a c3js visualization

I have a bar chart that looks similar to the one presented in this example. There are two specific features I am interested in adding to this bar chart: Instead of numeric values, I would like the tooltip title to show the sum of the counts represente ...

Is it possible to create a secondary <li> dropdown menu using JavaScript or jQuery from a PHP-generated dropdown menu?

Using a foreach loop to query the database, I have created a drop-down menu. Now, what I want is that when I select a subitem from the menu using JavaScript, I can retrieve the value and make an Ajax request to fetch all the values corresponding to the su ...

Emphasize the Jqgrid row when clicked on, but do not check the multiselect checkbox

Is there a method in jQgrid to highlight a row when clicked without selecting the multiselect checkbox? I attempted using Multiboxonly = true as suggested by Oleg on Your assistance would be greatly appreciated, as this issue is currently hindering progr ...

Consecutive pair of JavaScript date picker functions

My issue involves setting up a java script calendar date picker. Here are my input fields and related java scripts: <input type="text" class="text date" maxlength="12" name="customerServiceAccountForm:fromDateInput" id="customerServiceAccountForm:from ...

Tips for identifying modifications in an input text field and activating the save button

Currently, I am developing a function that can detect any changes made in the text field and then activate the save button accordingly. This code is being executed in Visual Studio 2017, using HTML and JavaScript. (function () { var customer_addres ...

Unable to add new tags in Vue multiselect component

Currently, I am utilizing a Vue Multiselect instance with two functions. One function interacts with the database to provide autocomplete functionality, which is working successfully. The second function allows for adding new tags that are not present in t ...

Inaccessible " following the "Return" Conflict

I'm struggling to resolve these warnings: Merge this with the previous "var" statement, found on lines 7, 9 and 10. Unreachable " after 'Return' - it's related to ($window.width() <= 770) { return; Script snippet: //StickyB ...

Clearing a leaflet layer after a click event: Step-by-step guide

When working with my map, I attempt to toggle the layer's selection using a mouse click. Initially, my map looks like this: https://i.sstatic.net/lOI95.png Upon clicking a layer, my goal is to highlight and select it: https://i.sstatic.net/63Rx2.pn ...