Using ng-options within an ng-repeat

I'm facing a unique issue with Angular where my select list has an empty first option. What's interesting is that when the select tag is placed outside of ng-repeat, there is no blank default value. However, when using the ng-option attribute within ng-repeat, I encounter the empty option problem. I've attempted to set the default value for ng-model on the select tag but it hasn't worked so far. Here's the html snippet:

<tr ng-repeat="item in todo.items">
  <td>{{item.project}}</td>
  <td>{{item.action}}</td>
  <td>
    <select ng-model="ttdSelect" ng-change="moveItem(item.id, ttdSelect);" ng-options="option.name for option in todo.options track by option.name">    
    </select>
  </td>
</tr>

Javascript:

var items = [{"id" : 1, "name" : "ttd" , "action" : "do it"}];

var selectOptions = [{ "name" : "next", "value" : "nextUp"},
                       { "name" : "in progress", "value" : "inProgress"},
                       { "name" : "waiting", "value" : "waiting"},
                       { "name" : "done", "value" : "done"},
                       { "name" : "trash", "value" : "trash"}];

app.controller("appController", function ($scope)
{
  $scope.todo.items = items;
  $scope.todo.options = selectOptions;
}

Answer №1

Just like jusopi's answer, but with a twist - presenting it in a SO snippet:

var app = angular.module('myApp', []);

var items = [{
  "id": 1,
  "name": "ttd",
  "action": "do it"
},
{
  "id": 2,
  "name": "zzz",
  "action": "do it 2"
}];

var selectOptions = [{
  "name": "next",
  "value": "nextUp"
}, {
  "name": "in progress",
  "value": "inProgress"
}, {
  "name": "waiting",
  "value": "waiting"
}, {
  "name": "done",
  "value": "done"
}, {
  "name": "trash",
  "value": "trash"
}];

app.controller("appController", function($scope) {
  $scope.todo = {};
  $scope.todo.items = items;
  $scope.todo.options = selectOptions;
  
  angular.forEach($scope.todo.items, function(item, key) {
    item.ttdSelect = $scope.todo.options[0];
  });
});
<!DOCTYPE html>
<html ng-app="myApp">
<head>
  <meta charset="utf-8" />
  <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c9a8a7aebca5a8bbe7a3ba89f8e7fde7b1">[email protected]</a>" src="https://code.angularjs.org/1.4.8/angular.js" data-semver="1.4.8"></script>
  <script src="app.js"></script>
</head>
<body ng-controller="appController">
  <div>
    <table class="table">
      <tr ng-repeat="item in todo.items">
        <td>{{item.project}}</td>
        <td>{{item.action}}</td>
        <td>
          <select ng-model="item.ttdSelect" 
          ng-change="moveItem(item.id, item.ttdSelect);" 
          ng-options="option.name for option in todo.options track by option.name">
          </select>
        </td>
      </tr>
    </table>
    <b>Trace:</b>
    <pre>
  items = {{todo.items | json}}
  </pre>
    <pre>
  options = {{todo.options | json}}
  </pre>
  </div>
</body>
</html>

Answer №2

Understanding your request was a bit challenging, so I approached it the way I typically tackle similar problems.

For an example, you can check out http://codepen.io/jusopi/pen/PZzxPY

Here are some of the issues I identified and resolved in your code:

  • ttdSelect seemed to be undefined, so I assumed it should update the status value of the todo item by assigning it to item.status
  • I set up a status option that matches a falsy value when a todo item lacks a current status
  • To enhance readability, I showcased how you can use ng-repeat on the <option> element in place of ng-options on the <select>

Hopefully, these changes prove helpful. Please note that I implemented this in jade/coffeescript for efficiency and effectiveness. If needed, you can easily review the compiled html/js code.

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

Sort an array by mapping it in decreasing order based on the total sum of its elements

I came across a JSON structure that looks like the following: { "user": [ {"username": "x1", "pfp": "", "scores": [{"easy": 10, "normal": 1, "hard": 2, "oni&q ...

Select the hidden HTML option value automatically according to the previous option selected

I am working on a form that includes 2 select tags with the options male and female. The first select, "gender", is visible to the user while the second select, "age", is hidden. <select name="gender"> <option value="1">Male</option> ...

Error: The function imgPreload cannot be executed because $ is not recognized as a function

I'm encountering an issue with calling a JavaScript function. Here's the code snippet I'm using: <script type="text/javascript" src="<?php echo base_url().'assets/'?>js/jquery-1.9.0.min.js"></script> <script t ...

What sets Vuex apart from a traditional store object?

I'm currently utilizing Vuex for Vue 2 which is similar to Redux for React. Recently, I came across a helpful example that demonstrates updating a counter. Here is the code snippet: import Vuex from 'vuex' import Vue from 'vue' V ...

"Exploring the symbiotic relationship between Node.js and Express.js: an

I recently started learning Node.js and Express.js. I used the Express.js executable (express) to create an express application, which generated the following lines in app.js: ... var app = express(); http.createServer(app).listen(app.get('port' ...

Angular 4 is displaying an error message indicating that the expression has been modified after being initially verified

I've been utilizing Angular Material within my Angular 4 application. There seems to be an issue when attempting to utilize the MatSnackBar in the ngAfterViewInit(). The error I encounter is as follows: ExpressionChangedAfterItHasBeenCheckedError: ...

The files being requested by jQuery Slimbox are not being retrieved properly

I am currently utilizing jQuery slimbox along with its Application Programming Interface (API). Below is the JavaScript code snippet that retrieves image paths through JSON and then triggers the slimbox using its API. $('#main-container').appen ...

Vue composable yields a string value

I am currently using a Vue composable method that looks like this: import { ref } from 'vue'; const useCalculator = (num1: number, num2: number, operation: string) => { const result = ref(0); switch (operation) { case 'add& ...

Discover how to use your own search engine suggestions within the search bar of Google Chrome

I recently created a search engine on my website, and everything seems to be working perfectly when I visit the search page. However, I wanted to streamline the process by searching directly from the search box in Chrome. After adjusting the settings to ...

Enhance and modify data with AngularJS, while also incorporating new information into the

Working on a feature where Worklists can be added and edited or deleted from local storage. Encountering an issue where after editing a worklist, it cannot be added anymore as it updates the existing worklist data that was selected for editing. (the edite ...

The functionality of Ajax is limited when it comes to handling multiple div elements at the same

Seemingly silly question ahead, but I've been grappling with it for days to no avail. If anyone can help me solve this, please state your price and provide your PayPal details – the money is yours :). What I'm trying to achieve is to add a "Add ...

Reset the dropdown menu in React by setting a disabled option as the default selection

One issue I'm facing is trying to reset some dependent dropdowns that are controlled by react state. The functionality works fine, except when the default option is set as disabled. I came across this code snippet in a fiddle from another stackoverfl ...

Is there a way to instruct Google to include my site in its index using Angular.js?

I am currently working on an angular.js app and have been following Google's guide for ajax-based applications. Here are the steps I have taken: Added meta tags <base href="/"> <meta name="fragment" content="!"> Configured angular.js ...

Changing API endpoints dynamically in AngularJS services according to the domain or host application

I have a MVC web application that utilizes AngularJS and a Web API. Both applications are deployed on separate domains. Whenever I make code changes and commit them, TFS automatically deploys both the MVC app and the Web API. Through web.config transformat ...

Issue with Angular 1.2: The .ng-move class from ngAnimate is not being applied

Angular's animate-repeat is causing some confusion for me. The ng-move class doesn't seem to be applied when I believe it should, making it difficult for me to create the animation I desire. In my code, I am utilizing ng-repeat with a custom fil ...

`Angular Image Upload: A Comprehensive Guide`

I'm currently facing a challenge while attempting to upload an image using Angular to a Google storage bucket. Interestingly, everything works perfectly with Postman, but I've hit a roadblock with Angular Typescript. Does anyone have any suggesti ...

AngularJS attempted to open $modal, but it encountered an error because the controller named <controllername> was not registered

Currently, I am in the process of enhancing a web application that was originally developed using AngularJS with typescript instead of JS. I have a controller set up with a specific template that I want to display in a modal using $modal.open. However, I ...

What is the best way to sort out the <li> elements within a <ul> that has a specific id

<ul class="apple" id="A"> <li> <li> ..... ...... ...... </ul> <ul class="apple" id="C"> <li> <li> ...

Customizing the default button in Ant Design Popconfirm to display "Cancel" instead

When the Ant Design Popconfirm modal is opened, the Confirm ("Yes") button is already preselected. https://i.stack.imgur.com/bs7W7.png The code for the modal is as follows: import { Popconfirm, message } from 'antd'; function confirm(e) { c ...

Including a property to a designated React component type at any depth within the DOM hierarchy

Looking to incorporate a "position" prop into the 'Child' components and utilize it within the 'Parent' component, the sole function of the 'PositionWrapper' is to add this one prop and return the modified children. Encounteri ...