Creating dynamic ng-options in AngularJS

Below is an array:

$scope.age = 2;
$scope.people = [{name:"Sam",age:2},{name:"Pam",age:3},{name:"Ham",age:4}]

The requirement is to make the ng-options dynamic. When age is 2, display all people objects in ng-options. If age is 1, show only the object with the name "Sam".

The $scope.age variable can be either 1 or 2.

How can this functionality be achieved in AngularJS without having separate select statement blocks for each condition?

Answer №1

You can link the select to a function's output:

<select ng-options="person as person for person in fetchPeople()">
</select>

Set up your scope as follows:

$scope.age = 2;
$scope.people = [{name:"Sam",age:2},{name:"Pam",age:3},{name:"Ham",age:4}]
$scope.fetchPeople = function() {
    if ($scope.age = 1)
        return $scope.people.filter(function(item) {
            item.name == "Sam";
        });
    else
        return $scope.people;
};

Answer №2

Utilizing the ng-options directive allows for filtering with filters, enabling scenarios such as this:

<select ng-options="person as person for person in people | filter:{age:age}">
</select>

For a demonstration, check out this jsfiddle

Answer №3

If you want to utilize AngularJS filter, you can do so by implementing a custom function.

Here is a functional example: (enter 1 or 2 in the input field below to experiment with this)

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

app.controller('TestController', function($scope) {
  $scope.age = 2;
  $scope.people = [{name:"Sam",age:2},{name:"Pam",age:3},{name:"Ham",age:4}];
  $scope.filterPeople = function(person) {
     return $scope.age === 2 || person.name === "Sam";
  };
});

angular.bootstrap(document, ['app']);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-controller="TestController">
  Age: <input type="text" ng-model="age" />
  <select ng-options="person as person.name for person in people | filter:filterPeople" ng-model="selected">
  </select>
</div>

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

Creating a stroke in SVG using JavaScript

I created a code that inserts a line into my svg page when I press a button Here is the html snippet: <body> <svg width="500" height="400"> </svg> <button id="btn1">Append text</button> </body> Below is the script us ...

Searching for a pattern and replacing it with a specific value using JavaScript

I need to find all occurrences of an unknown string within a larger string that is enclosed in brackets. For example, the string may look like: '[bla] asf bla qwr bla' where bla is the unknown string I need to locate. Is it possible to achieve th ...

Changing the value of a variable after iterating through an array in JavaScript

I'm just getting started with programming and teaching myself. I'm struggling to grasp how to update a variable by iterating through an array. Here's an array containing the best pies, each with its own price: [blueberry, strawberry, pumpk ...

Utilize this JavaScript tool to effortlessly transform an XML string into JSON format

Looking for the optimal javascript function, plugin, or library to effectively transform an XML string into JSON format. One tool I came across is , but unfortunately, it struggles with strings that begin with 0. For example, 005321 may end up converted t ...

Using node.js to send custom data over a websocket

I came across an excellent tutorial on websockets. In this tutorial, the server decodes and writes a message to the console whenever it receives a message from the client. After that, the server sends the message back to the client. var firstByte = data ...

Extract information from a specific div element and save it to a text file

I'm currently working on extracting data from a div and sending it to a PHP file using the following JavaScript: $(document).ready(function(){ $('#save').on('submit',function(e) { var bufferId = document.getElementById ...

When attempting to log API results in Next.js, a TypeError occurs because the property is undefined

I'm encountering a rather unusual error. In my Next.js app, I am attempting to console log the results of an API call to see what data I receive. The API function is responsible for verifying if a user is logged in, and if they are, I render a specifi ...

Checking email existence through remote jQuery validation

Utilizing the jQuery validator plugin, I am implementing an ajax function with a remote method to validate whether an email already exists in my database. However, I am encountering an error when making the ajax call within my validation function. "email ...

Tips for implementing a nested ng-repeat with nested JSON array data triggered by a button click

Assuming I have assigned the following JSON data to $scope.people: [ { "personId": 1, "name": "Thomas", "age": 39, "friends": [ { "friendId": 1, "nickName": "Lefty" ...

Objective subject for an element within a :not operation

I have a function that specifically excludes a style on links by targeting their IDs. Each of my links has an ID, so I use that to exclude the style. a:not([id='hopscotch_logo'] { color: red; } Now, I also want to find links that are children o ...

What is the best way to handle .jsx files in my library bundling process with Rollup?

Currently, I am in the process of developing a component library using storybook and rollup. Here is the configuration file rollup.config.mjs /* eslint-disable import/no-extraneous-dependencies */ import peerDepsExternal from 'rollup-plugin-peer-deps- ...

Why isn't pagination typically positioned inside of a tbody element rather than before or after it?

I've created a user table that is based on the number parameter. I added a filter that listens to input and performs an AJAX call each time with the filter applied to the name field. However, the pagination is initially displayed ABOVE the entire ta ...

Switch off JavaScript beyond the parent element

Struggling with implementing an event to toggle a div using an element located outside of the parent container. I am attempting to achieve the same functionality by targeting elements beyond the parent structure utilizing a span tag. Any assistance on th ...

JavaScript can be used to append multiple array values within double brackets in Spring MVC

I am currently developing an application using Spring MVC with MongoDB. In the collection, I have retrieved multiple image name values: Ex: 1.jpg, 2.jpg, 3.jpg.... My Query: Now I need to place these values inside double brackets [[]] Ex : [["1.jpg"," ...

The button effortlessly transforms into a sleek email submission form

I have a button that is already styled with basic CSS properties for active and hover states. I would like to add functionality so that when the "Join the Loop" button is clicked, it transforms into a simple email form similar to the one found at Apologie ...

I have successfully implemented ngCordova local notifications, but now I am looking for a way to make it trigger for each individual

Is there a way to trigger a notification on every logged-in user's mobile device when a value is changed and saved in Firebase? Currently, I am able to send a local notification using ngCordova when a user enters text in an ionicPopup with textarea. H ...

Leverage the `dispatch` hook within a useEffect function

When it comes to triggering an action upon the React component unmounting, I faced a challenge due to hooks not allowing the use of componentWillUnmount. In order to address this, I turned to the useEffect hook: const dispatch = useDispatch(); useEffect(( ...

Detecting Image Loading with Javascript

My website is filled with numerous images categorized into 5 different groups, causing it to load slowly. To improve loading times, I have assigned each image a "data-src" attribute containing its actual source. Then, when a specific category is selected ...

Error: An unexpected token '<' was encountered during the React Webpack build process

My ReactJs project is using Webpack4 and @babel/core 7. However, when I attempt to build the project, I encounter the following error in the terminal: ERROR in ./src/views/Pages/Login/Login.js Module build failed (from ./node_modules/babel-loader/lib ...

How to sync two carousels in Bootstrap 5 to slide simultaneously with just one click on the next and previous buttons

I am trying to implement dual sliding carousels using Bootstrap 5, but I am encountering issues with getting them to slide simultaneously. Despite incorporating data-bs-target=".carousel", the synchronization isn't working as intended in my ...