The option chosen from the ng-options does not remain attached to the drop-down menu

I need some help with AngularJS as I am still getting the hang of it.

Take a look at this not-so-pretty page: https://i.sstatic.net/Dtm7j.png

This page allows users to add new beers, and each beer can have multiple styles. Clicking 'Add' creates a new dropdown for selecting a style, while clicking 'Remove' removes an existing one. The issue is that selected styles do not appear in the dropdown after selection - they remain empty once collapsed or closed.

Here is the code snippet:

Beer View

   <div class="form-group" ng-repeat="style in beer.styles">
        <label for="style" class="col-sm-1 control-label" ng-if="$index == 0" >Style</label>
        <div class="col-sm-1" ng-if="$index > 0">
          <button type="button" class="btn btn-danger" ng-click="removeStyle($index)">Remove</button>
        </div>
        <div class="col-sm-10">
          <select class="form-control"
                  ng-controller="styleCtrl"
                  ng-model="selectedStyleId"
                  ng-options="style.id as style.name for style in styles"
                  ng-change="updateStyle($index, selectedStyleId)">
          </select>
        </div>
        <div class="col-sm-1">
          <button type="button" class="btn btn-primary" ng-click="addNewStyle()">Add</button>
        </div>
      </div>

Style Controller (Dummy Impl)

.controller('styleCtrl', ["$scope", "$location", function ($scope, $location) {
  $scope.styles = [
    { 'id': '1',
      'name': 'Lager' },
    { 'id': '2',
      'name': 'American Blonde Ale' },
    { 'id': '3',
      'name': 'American Stout' },
    { 'id': '4',
      'name': 'Cream Ale' },
    { 'id': '5',
      'name': 'Bock' },
    { 'id': '6',
      'name': 'German Pilsener' }
  ];
}]);

Beer Controller

.controller('beerCtrl', ["$scope", "$location", function ($scope, $location) {
  $scope.beer = {
    'styles': [
        { 'id' : '-1' }
    ]
  }

  $scope.addNewStyle = function() {
    $scope.beer.styles.push({ 'id': '-1' });
  }

  $scope.removeStyle = function(index) {
    $scope.beer.styles.splice(index, 1);
  }

  $scope.updateStyle = function(index, styleId) {
    $scope.beer.styles[index] = { 'id': styleId };
  }

Although the styleId is correctly recorded in the array, the display on the screen is where the problem lies.

Do you notice any mistakes in my code?

P.S.: I suspect that having two controllers - BeerController and a 'nested' StyleController - in the same view might be causing the issue.

Answer №1

Being a newcomer to AngularJS, I made a simple mistake by directly binding the selected value to the backing object instead of using on-change:

 <select class="form-control"
          ng-controller="styleCtrl"
          ng-model="beer.styles[$index].id"
          ng-options="style.id as style.name for style in styles">

Fortunately, that did the trick. It was just a silly oversight on my part.

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

Calculating the total sum of values in a table using Jquery

Can anyone help me calculate the sum of input values from a table using HTML and jQuery? Here is my current code: HTML: <tr id='saved1'> <td><input class='qty'/></td> <td><input class='price&apo ...

The slideUp function is not functioning as expected

I am trying to implement a slideUp effect on my webpage. Here is the code within my <body> tag: <script> $('#slide_up').click(function(){ $('p.text_study').slideUp('slow', function() { $ ...

Synchronize your store by utilizing cookies in the nuxtServerInit function of NuxtJS

I am currently working with NuxtJS's auth module and attempting to retrieve the Bearer token along with a custom cookie that holds a sessionType during nuxtServerInit in order to update the store through a mutation. However, I am facing an issue where ...

Tips for effectively packaging the React 17 library alongside the latest JSX transformation feature as an ES Module

I am currently in the process of creating a basic library consisting of React components that I intend to publish as an ES Module package for NPM. With the utilization of React 17, I have incorporated the new JSX transform into my code. To generate the ES ...

Updating data from an API within a div using AJAX calls in a React application

I have designed a React template to showcase live football scores in the following manner: const LiveScore = () => { const {direction} = useThemeProvider(); const [selectedDay, setSelectedDay] = useState(parseInt(dayjs().format('DD'))); retur ...

What is the best way to pass a variable in an AJAX function call when making a POST request?

I am facing an issue with sending a variable through an ajax function. The scenario is as follows: <a href="next.php" onclick="sendajax()">reload</a> I need to send this variable via the POST method in my php page: <script> fu ...

Incorporate a controller into another controller on the fly using AngularJS

Within my application, I utilize a wrapper controller to manage certain properties dynamically based on the presence of other-controllers nested within it. While everything functions perfectly when the other-controllers are static upon loading, issues aris ...

What sets these async method declarations apart?

What goes on behind the scenes? const facade = { // A: doSomething: async () => await delegatedFunction(), // B: doSomething: async () => delegatedFunction(), // C: doSomething: () => delegatedFunction(), // D: do ...

MUI input remains static and unaltered

I tried to switch from my regular input to a Material-UI text field. Everything was working fine before, but now the value isn't changing. const handleChangeInput = (e) => { const { name, value } = e.target; console.log(e.target.value); ...

The component briefly displays the previous state before updating in the Material-UI Alert component

Whenever there is an error from an API while a user is registering, an alert is displayed on the form page. To handle this, an Alert component was created: <Snackbar open={open} autoHideDuration={9000} onClose={() => { setOpen(f ...

Creating an internal network using MVC, EntityFramework, AngularJS, and Breezejs?

Looking to embark on a learning project, I aim to develop a straightforward intranet application (featuring functionalities such as login/logout, user creation, project management, etc.) by incorporating some new libraries/frameworks. However, I am uncert ...

Creating a consistent base URL for both Vue and Apache reverse proxy configurations

Currently, I am experimenting with a Vue app and testing it using pm2 in conjunction with Apache. After starting the app with pm2 and running it on port 3000, I then utilize an Apache reverse proxy to access the app through a domain and HTTPS. However, I e ...

Unable to deploy the Firebase function to Firebase functions platform

I've been watching Doug's video on YouTube for guidance on changing a message with functions in JavaScript. To resolve the error message 'types can only be applied to ts files,' I installed the Flow language script. Thankfully, that err ...

The form is not being submitted when I click on the submit button because I have two buttons that trigger AJAX requests

I am facing an issue with a form where there is a submit button inside it, as well as another button within the form that has attributes type=button and onclick=somefunction(). The button with the onclick function works perfectly fine, but the other button ...

Utilizing JavaScript to dynamically adjust the height of one div to match the height of another div

Struggling to adjust the height of one div to match another using the following code: var aboutheight=document.getElementById('about').offsetHeight; document.getElementById('sampledogs').setAttribute("style","height:aboutheight"); Des ...

Within the ASP.NET Framework 4, it is necessary to enable the Listbox control to trigger an event when a user double

Currently, I am developing a project in ASP.NET 4. I have encountered a situation where the regular ListBox in version 4.5 includes an attribute named OnMouseDoubleClick. However, since I am using ASP.Net 4, I am looking for the best approach to replicat ...

Enabling block scrolling on a parent element using jscrollpane functionality

Is it possible to set up a jscrollpane so that the parent pane doesn't scroll when the child scroll has reached its bottom? Currently, when the child scrolling reaches the bottom, the parent also scrolls. I would like the parent to only scroll when th ...

Why isn't the click event triggering MVC 5 client-side validation for ajax posts?

To incorporate client-side validation with a click event for ajax posts, I followed a guide found at the following URL: Call MVC 3 Client Side Validation Manually for ajax posts My attempt to implement this involved using the code snippet below: $(&apos ...

Unraveling the Power of Recursive Functions within a React.JS

I'm encountering an issue with a React project. It involves a tic tac toe game where I'm currently working on the implementation of the computer player. The problem arises when the human player clicks on one square (Field-component), triggering ...

An individual referred to as "User" is currently not defined, despite

I am currently working on a react application and I'm facing an issue where the App component does not seem to be receiving my user value even though it is present. Interestingly, the same syntax works perfectly fine in other components. The error me ...