Assigning a default value to a select dropdown using objects in Angular

I am in need of assistance. I am struggling to convert $scope.headline.category into an object; it must remain a string. The groupList needs to be a list of objects. Is there a way to set the initial value of the dropdown to the 2nd item (1 index) without having to do it through the controller? Perhaps utilizing ng-init? Thank you for any guidance.

My unsuccessful attempt:

ng-init="headline.category = group.label"

The solution that works, but I feel like there should be a simpler approach:

for (var a = 0; a < $scope.headlineList.length; a++) {
    for (var b = 0; b < $scope.groupList.length; b++) {
        if ($scope.headlineList[a].category == $scope.groupList[b].label) {
            $scope.headlineList[a].category = $scope.groupList[b];
        }
    }
}

Angular

$scope.headline.category = "B";
$scope.groupList = [ {label: "A"}, {label: "B"}, {label: "C"} ];

HTML

<select ng-model="headline.category" ng-options="group.label for group in groupList"></select>

Answer №1

I believe the controller only requires the following code:

app.controller('MyCtrl',function($scope){
      $scope.headline = { category: "B" }
      $scope.groupList = [ {label: "A"}, {label: "B"}, {label: "C"} ];
  });

Additionally, the select should be changed to:

<select ng-model="headline.category" ng-options="group.label as group.label for group in groupList"></select>

The important modifications include setting the headline object to { category: "B" } (likely retrieved from an ajax call) and using group.label as at the start of the options to specify the value from the category objects for the model.

Here's a Plunk example

Answer №2

UPDATED Check out the revised code:

<select ng-model="headline.category" ng-init="headline.category = groupList[index]" ng-options="group.label for group in groupList"></select>

Controller:

angular.forEach($scope.groupList, function(value, key) {
      if(value.label == $scope.headline.category){
          $scope.index = key;  
      }
  });

PLUNKER with a demo.

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

React: I am looking to incorporate two API calls within a single function

I am currently learning ReactJS and focusing on implementing pagination. My goal is to fetch page data from a server using an API, with Loopback being the tool for API integration. The initial setup involves displaying a list of 10 entries on the first pag ...

Adding new elements to an array does not activate the reactivity of Vue

After discovering that editing objects within an array doesn't function properly in vue.js due to its limitations, I tried using vue.set to resolve the issue, but it's proving to be quite challenging for me. Let's take a look at the sample ...

The use of '-' in v-bind:style within Vue.js

I'm having trouble figuring out how to use CSS code with dashes in v-bind:style. When I attempt something like this: <DIV style="width:100px;height: 100px;background-color: red;cursor: pointer;" v-bind:style="{ margin-left: margin + 'px' ...

Fully responsive header designed for optimal experience at any screen height

I am facing issues with the header and cannot seem to find a solution. My goal is to make the header span 100% of the window screen height. I need a responsive header that adjusts to 100% height, and when resizing for a smaller viewport, nothing should sho ...

Guide to utilizing a directive for dynamic template modifications

I am facing a challenge with this specific instruction. angular.module('starter.directive', []) .directive('answer', ['Helper', function (Helper) { return { require: "logic", link: function ...

The concept of DIV layers and utilizing the jquery click function

My project includes a cool postcard feature that involves animating an overlay div and displaying a postcard on top of it. Here's a snippet of the HTML code: <div id="overlay"> <div class="postcard"> <p>This is a postcar ...

Consolidate multiple generic items into a single entry

In my current project, I am structuring the types for a complex javascript module. One of the requirements is to handle multiple types using generics, as shown in the snippet below: export interface ModelState< FetchListPayload, FetchListR ...

Issue encountered while trying to run Bower Install: Unable to establish connection with an exit code of #128

I encountered a problem while trying to run bower install. bower ECMDERR The command "git ls-remote --tags --heads HTTPS_LINK to bower-angular-mocks.git" failed with an exit code of #128 After seeking advice from Git / Bower Errors: Exit Code ...

What could be the reason that my JSON request is not functioning properly?

I am currently working on creating a movie search application. This project marks my first time delving into json and I'm facing some issues with my code. As of now, I have it set up and running smoothly on localhost through xampp. On submitting the ...

What is the best way to have a single item in a list displayed in two columns?

Can the angular repeat achieve this functionality? I am looking to loop the two elements together. Any assistance would be greatly appreciated! Controller: $scope.date=[ {ID:1,Date:'2016-11-12'}, {ID:2,Date:'2016-11-15'}, ...

Is there a method to determine whether the user has granted permission for notifications to be enabled?

Once I have requested permission from the user of the website, I need to confirm if they have granted permission before triggering the send() function. What is the most sophisticated approach to achieve this? ...

Issue with Saving Query Loop Results in Prisma MySQL with NextJS/ReactJS

I'm struggling with a Prisma query that is giving me grief. Despite my best efforts, I can't figure out why it's not functioning properly. The getImages() method below is intended to retrieve all the images associated with a product. Query ...

The console is showing messages before the task is completed

When using console.log to write detailed messages about the current task expected to be performed by Protractor, I noticed that these messages are appearing on the console before the actual task is executed in the browser. An example of this is: it(' ...

Transforming FormData string key names into a Json Object that is easily accessible

Recently, I encountered an issue where my frontend (JS) was sending a request to my backend (Node Typescript) using FormData, which included images. Here is an example of how the data was being sent: https://i.stack.imgur.com/5uARo.png Upon logging the r ...

Is there a workaround in TypeScript to add extra details to a route?

Typically, I include some settings in my route. For instance: .when('Products', { templateUrl: 'App/Products.html', settings: { showbuy: true, showex ...

Shift attention away from AG-Grid

AG Grid is being used on a website and when a user clicks a cell, it becomes focused with a blue outline. I am looking to remove this focus when the user clicks on specific elements on the site, but I am unsure of how to achieve this. Is there a method or ...

Ensure that test cases in Angular2 include a line that covers conditions for returning values

I'm having trouble implementing test coverage for an online platform, as I'm not sure how to approach it. Within my service method, I have the following code: public getResults() { return this.http(url,body).map(this.mapResponse); } private ...

Switching from using a computed property in Vue 2 to implementing the Vue 3 Composition API

I am currently in the process of updating my Vue 2 application to Vue 3 and I have been exploring how to work with computed properties using the Composition API in Vue 3. One particular challenge I am facing is migrating a Vue 2 computed property that pro ...

Utilizing Node.js and Mongoose, effortlessly update data in Mongo DB regardless of the existence of the collection

How can I update a field that may or may not exist? I attempted the following code: db.foo.update( { site: '"wisdom'}, { $set: {'club': 'fc barcelona'}}, (upsert=true) ) ...

The issue of the marker vanishing upon refreshing the page on AngularJS

Currently, I am encountering a rather peculiar issue. Upon the initial page load, the code snippet below correctly displays a marker at the specified coordinates and ensures the map is properly centered: <div class="paddingtop"> <map data-ng- ...