Dynamic value in Angular select using ng-initExperience the power of Angular select

When working with Angular, I encountered an issue trying to set a default value for a select box using ng-init from an object that is generated during runtime. Here's the code snippet that's causing me trouble:


    <select 
        ng-model="settings.editing.panel.data.production_company"
        ng-change="settings.editing.panel.data.production_company = selectValue"
        ng-init="selectValue = settings.editing.panel.data.production_company"  
    >
        <option 
            ng-repeat="(key, value) in lists.production_companies" 
            value="{{key}}"
            ng-selected="{{selectValue}}" 
        >
            {{value}}
        </option>
    </select>

The source of my problem seems to be that "lists.production_companies" is an array of names populated at page load and updated via ajax.

The initial state of the object "settings.editing.panel.data" is NULL but it gets loaded later on with a properly formatted object that includes the property "production_company".

I've tried setting ng-init to static values like "ng-init="selectValue = 3" and even creating a $scope.test variable, assigning it a value then using it for ng-init. Both methods work fine.

However, when trying to use a dynamic value, I'm facing issues. How can I leverage my dynamically created object to establish the value of this select box during runtime within my current set-up?

Answer №1

<div 
            ng-model="settings.editing.panel.data.production_company"
            ng-options = "option as option.keyName for option in list.production_companies"
        > <!--make sure to match keyName with your object's key-->

        </div>

Next step is in your controller

$scope.settings.editing.panel.data.production_company = list.production_companies[0] // Choose the value you want to assign

Answer №2

Your inquiry has left me a bit perplexed. Below is a snippet of code that appears to be functional. Is this what you were looking for?

'use strict';
angular.module('DemoApp', []);
angular.module('DemoApp').controller('DemoCtrl', ['$scope', function($scope){
  $scope.lists={
  production_companies: { "0": "prod 1", "1":"prod_2" },
  };
  $scope.settings={
  editing: {
    panel: {
      data: null
      }
    }
  };
  $scope.setData=function(data){
    $scope.settings.editing.panel.data={
      production_company: data
    };
  };
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="DemoApp" ng-controller="DemoCtrl">
<select ng-model = "settings.editing.panel.data.production_company">
  <option ng-repeat = "(key, value) in lists.production_companies" value = "{{key}}">{{value}}</option>
</select>
<div>You select: {{settings.editing.panel.data.production_company}}</div>
<button ng-click="setData('0')">Set Data to Prod1</button>
<button ng-click="setData('1')">Set Data to Prod2</button>
</div>

Answer №3

When faced with similar circumstances, I made changes to my backend's data format by setting an object as follows:

{"id": 1, "name":"prod comp 1"} 

This allowed me to adjust my select model accordingly, particularly for the ID requirement that became apparent later on.

<select 
    ng-model="settings.editing.panel.data.production_company"
>
    <option 
        ng-repeat="option in settings.lists.production_companies" 
        value="{{option.id}}"
        ng-selected="{{option.id}} == settings.editing.panel.data.production_company"
    >
        {{option.name}}
    </option>
</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

Is there a way to automatically update the URL to include $_GET['data'] (media.php?data=123) when a selection is made from a dropdown list?

I'm currently working on a project that involves a website in PHP and a MySQL database. I have successfully linked the two together, and now I have a combobox filled with data from the database. Below is my script for handling the selection: <scr ...

Guide to Triggering a Page View Event in Google Tag Manager with Angular

Previously, I manually fired the Page View Event using JavaScript from app.component.ts while directly accessing Google Analytics: declare var gtag: Function; ... constructor(private router: Router) { const navEndEvents = this.router.events.pipe( fil ...

Node.js is great at hosting HTML files, but struggles when it comes to loading script files within those pages

Recently, I’ve been working on creating a simple login page using a mongoDB database along with Node.js and express. Since I'm still new to Node.js, I'm facing an issue that seems more complicated than it actually is. The main problem I’m en ...

The function history.popstate seems to be malfunctioning, as it is triggered by both the forward and backward navigation buttons in

When I press the back button, I am attempting to retrieve the previous state. Upon inspecting, I noticed that the popstate function is also triggered by the forward button. However, it does not revert to the previous state even though the popstate function ...

Warning: Attempting to modify a property that is not defined - 'action'

My code includes a datatable and an alert that pops out. The datatable functions properly with or without the alert, but the alert does not work well when combined with the datatable. Could this be causing a conflict in the code? An error message indicates ...

React revolutionizes the way we handle line breaks in

Just starting out in the world of coding and feeling a bit overwhelmed. I have checked out MDN, WJ3 but I'm still struggling with inserting line breaks into my code. return market.outcomes.map( ({ name, price ...

*ngIf doesn't seem to be functioning as expected compared to other *ngIf directives

Encountering a peculiar issue with my *ngIf related to the isAdmin variable which determines whether the list of users in userList should be displayed or not. Strangely, it seems to behave differently compared to other *ngIf statements within the same comp ...

How can we create a two-dimensional image with random dimensions using Math.random?

I am struggling to create a variety of flowers with different sizes from an Array. The issue I'm facing is that every time I click to add a new flower, it changes the size of all existing flowers as well. What I would like is for each added flower to ...

What is the best way to adjust the size of an image as I navigate down a webpage?

I've been working on designing a navigation bar for a website, but I'm running into some issues. My goal is to have the logo shrink as the user scrolls down the site. I've experimented with webkit animations and various javascript/jQuery fun ...

Using jqgrid to generate a hyperlink that corresponds to the data's value

I am working with a grid setup similar to the one below: $("#list").jqGrid({ url:'listOpenQueryInXML.php', datatype: 'xml', colNames:['Id','name1', 'name2', 'status', 'type' ...

Output object data to table by clicking on it - requires two clicks for the data to be

I have a situation where I want the user to click a button in order to print an object obtained from a web service into a table. The issue is that currently, I have to click the button twice for it to work properly. Here's some more detail: The button ...

Is a referrer included in AJAX requests made from the background page of a Google Chrome Extension?

Can anyone confirm if AJAX requests sent from the background page of my Chrome Extension will include referrer information? I'm wondering about this. Appreciate any insights you can provide! ...

Engage with and rearrange JSON data

Upon receiving data from the endpoint, I realized that it needed some modifications before being suitable for display in a table. The initial example data looks like this: const data = [ { Year: 2017, OriginalIntBalanceOverdue: 0.0, D ...

Discover how to access all of the response headers from an HTTP request in Angular

Currently, I am utilizing HttpClient to make a request for a `json` file. My intention is to have the file cached using `ETag`, however, this feature does not seem to be functioning as expected. Upon investigation, it appears that the absence of sending of ...

Combining strings within an HTML attribute

Within my custom directive, the template looks similar to this: template:'<li ui-sref-active="active" ng-class="\'has\'+ getSubClassString(item)">'+ '<a ui-sref="{{item.state}}">' + ...

The switch statement within Angular returns null when using getElementById()

In my single page application, I am using ng-switch to switch between different 'pages'. One of these pages contains a modal that is opened using the following function: var modal = document.getElementById('myModal'); vm.openModal = fu ...

Customize CKEditor by automatically changing the font family when the page is loaded

How can I change the font-family of CKEditor to Meiryo based on a JavaScript boolean? I attempted this code in my custom JS within an if condition, but it did not successfully change the font-family: config.font_style = { element : 'span&apo ...

What is the best way to manage photos from your phone without having to upload them online?

I'm currently developing an application using AngularJS/Javascript, HTML, and CSS within a cloud-based environment on c9.io. My next task is to create and test an app that can access the phone's photo album, apply filters to images, and I'm ...

Exploring the differences between a callback function and an asynchronous

In the code snippet below, I have implemented handling for SIGINT and SIGTERM signals in a node.js application. // quit on ctrl+c when running docker in terminal process.on('SIGINT', async () => { console.info('Got SIGINT (aka ctrl+c in ...

When scrolling, a new page loads seamlessly

Recently, I came across a website that has an interesting feature where new content is loaded automatically while scrolling, seamlessly appending to the existing page. What's more fascinating is that not only does the content change, but the URL also ...