Using ng-options AngularJS to narrow down a JSON object

I am facing a challenge with using AngularJS to filter a JSON object into a select form element. Here is the current progress I have made. I am stuck and would appreciate any assistance.

app.js:

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

app.controller('MainCtrl', function($scope) {
  $scope.showItems = null;
  $scope.items = [
    { id: '023', name: 'foo' },
    { id: '033', name: 'bar' },
    { id: '010', name: 'blah' }];
});

singlepageapp.html:

<html data-ng-app="app">
  <body data-ng-controller="MainCtrl">
    <form>
    <select data-ng-model="showItems" data-ng-options="item as item.name for item in items"></select>
    </form>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.min.js"></script>
    <script src="app.js"></script>
  </body>
</html>

current result:

<select data-ng-model="selectedItem" ng-options="item as item.name for item in items" class="ng-pristine ng-valid">
    <option value="?" selected="selected"></option>
    <option value="0">foo</option>
    <option value="1">bar</option>
    <option value="2">blah</option>
</select>

desired result:

<select data-ng-model="selectedItem" ng-options="item as item.name for item in items" class="ng-pristine ng-valid">
    <option value="?" selected="selected"></option>
    <option value="023">foo</option>
    <option value="033">bar</option>
    <option value="010">blah</option>
</select>

Answer №1

If you prefer, you can iterate through options directly in the HTML code instead of using data-ng-options. Check out this example I put together for you: http://jsfiddle.net/9PQ2R/

<select ng-model="selected">
    <option value="{{data.id}}" ng-repeat="(index,data) in dataList"> {{data.title}}
    </option>
</select>

By doing it this way, you can easily assign values using scoped variables.

I hope this solution works for you!

Answer №2

It would be helpful if you could provide the item.id

<select ng-model="selected" ng-options='item.id as item.name for item in items'>               </select>

Refer to http://docs.angularjs.org/api/ng/directive/select

Please note that ngOptions is recommended over ngRepeat when binding select models to non-string values, as option elements can only be bound to string values currently.

I have made updates to the jsFiddle http://jsfiddle.net/5MQ9L/2/

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

The error "Uncaught TypeError: Cannot read property 'render' of undefined" occurs when using Three.js along with OrbitControls

I am having an issue with my rotating cube class. Whenever I try to rotate or zoom the cube, I encounter an error message saying "Cannot read property 'render' of undefined". I suspect that the problem lies within the scopes. Below is my class im ...

When implementing a Vue component, you may encounter a 'parentNode' TypeError

I'm experiencing an issue with a page that is only partially rendering. Specifically, the page renders Listings but not Bookings. After some investigation, I discovered that removing the divs associated with isReviewed() resolves the rendering issue. ...

Add an array to an existing array of objects

I am working with an array of objects displayed below. var myArray = [ { Data: '455', Note: 'tre', Id: '4' }, { Data: '456', Note: 'bre', Id: '5' }, { Data: '457', Note: 'cre&ap ...

Combining and organizing JSON arrays

Having an issue with jq. Received the following data from API: { "items": [4,5,1,3,2], "objectNumbers": [ { "type": "objectNumber", "number": 8 }, { "type": "objectNumber", "number": 7 }, { ...

Develop a fresh JavaScript object by combining two JSON objects organized by their respective IDs

I have a challenge with two dynamic nested JSON object arrays and I am looking to achieve a specific output by grouping them based on their IDs using JavaScript. The structure of the first array is as follows: [ { "id": "11", "name": "emp1", ...

Receiving the error message "TypeError: Page is not a valid constructor."

Having trouble with the "Page is not a constructor" error message, despite trying various solutions. Initially suspected an issue with JQuery, but upon inspection, everything appears to be in order. "TypeError: Page is not a constructor." admin_pages.js ...

"Exploring the differences between sending a JSON post request with multiple parameters to a Web

Our transition from MVC to WebApi for data serving involves changing the controller structure, as shown in the example below. MVC: OfficeController : Controller { [HttpPost] public IEnumerable<Employee> SetSalary(string badge, string salary ...

Creating Cell Fracture Blender Animations with THREE.js

Recently, I completed a blender animation featuring a cube that shatters using cell fracture and then seamlessly comes back together when played in reverse. Check out this example below for reference: https://i.sstatic.net/GrJnV.jpg In my iteration of t ...

Having trouble accessing a local JSON file in electron-vue

I am attempting to retrieve a local JSON file in my project. I have tried the following: import axios from 'axios'; import userDataJson from './../data/userData.json'; export const userDataControllerMixin = { data() { return { ...

What is the method for calling a JavaScript function from one file to another within a Node.js environment?

Just starting out with JavaScript and exploring the idea of breaking the code into multiple modules. While working with nodejs, I've encountered an issue where it's complaining about pathChecker not being defined. Any insights on how to resolve t ...

While executing a jssor code in SP 2007, IE experiences freezing issues

I've integrated a jssor slider with vertical navigation (without jQuery) into a Sharepoint 2007 page using CEWP. All the image links have been replaced with images stored in the SP image library, and the jssor.slider.min.js file has been uploaded to t ...

Implementing dynamic components in Vuejs by passing props from objects

I have developed a dashboard application that allows users to customize their dashboard by adding widgets in any order. While the functionality is working fine, I am looking to address some technical debt and clean up the code. Let's simplify things ...

Adjust the length of the connection line in the Highcharts sankey diagram

I am in need of assistance with adjusting the length of connection lines in a Highcharts sankey-diagram. Can anyone offer guidance on how to do this? https://i.stack.imgur.com/1KjkF.png The spacing between data columns is currently too wide for my liking ...

Tips for manipulating HTML using JavaScript and detecting the updates in ASP.NET after a postback

This is a unique challenge, and despite my efforts to find a solution in various sources, I couldn't overcome this specific scenario. I want the user to input multiple values into a single text field, like this: <div style="margin-left: 5px; disp ...

Angular filtering options based on user input and model selection

In the jsbin demo provided, there is an input field, a select option, and a list of movies. The objective is to filter the list of movies in Angular based on user input in the input field and selection in the select dropdown. <div ng-controller="myCont ...

Exploring the characteristics of $scope elements generated by the $resource factory service within AngularJS

I need to access attributes of an object that originates from a $resource factory service (REST API). services.js: myApp.factory('userService', ['$resource', 'backendUrl', function($resource, backendUrl) { return $resource ...

Using jQuery to cycle through JSON information

When I try to display the output using an alert in the following example, I receive the correct result. However, if I use console.log instead, the output is shown as: Number {} "length": [ 20, 40, 60, 80 ], jQuery.each(length, function() { new_length ...

Bootstrap tooltip does not disappear when clicking on <a> tags

When using the hover trigger for a tooltip and clicking on a link with this function, the tooltip does not disappear, causing it to remain on the screen indefinitely. The tooltip is initialized with the following code: $('[data-toggle="tooltip"]&apo ...

What is the reason behind V8's perplexing error notification?

When running this code on Chrome or Node (v8), an error message is displayed: Uncaught TypeError: f is not iterable function f(){} f(...undefined); Why is such an ambiguous error message generated in this case? Does it really have nothing to do with ...

Tips for organizing static JSON files for XCTests

Currently, I have a collection of static json files within my project that I am utilizing in unit tests instead of API responses. In order for this setup to function properly, the target membership of these files must belong to the production target; other ...