Muddled understanding concerning the utilization of ng-options

I am struggling with ng-options, as I have created a dropdown from an array defined in my controller. Below is my HTML code:

<div ng-app>
<div ng-controller="testCtrl">
    <select multiple="multiple" ng-model="first" ng-options="c.name for c in listObj">
    </select>
    <select multiple="multiple" ng-model="second">
    </select>
    <hr/>
    {{first}}
</div>
</div>

Here is the corresponding JavaScript code:

function testCtrl($scope) {
    $scope.listObj = [{name: "x", content: [1,2,3]},
                      {name: "y", content: [4,5,6]}];

}

You can view the working jsFiddle here:

http://jsfiddle.net/zono/rkBUL/10/

My goal is to have the right select box populated with the corresponding content property when a user selects an element from the left select box. For example:

If a user selects "x" from the left box, the right box should display 1,2,3. If "y" is added to the left box, it should display 1,2,3,4,5,6. If "x" is deselected, it should display 4,5,6.

Thank you in advance.

Answer №1

To avoid using a $watch like @package suggested, you can create a helper function in your controller that unpacks each value of content for every selected item in listObj and stores them in an array for the ng-options of your second select element.

$scope.contents = function(arr) {
    var values = [];
    if (angular.isDefined(arr)) {
        arr.forEach(function(v) {
            values = values.concat(v.content);
        });
    }
    return values;
};

Then, use:

ng-options="c for c in contents(first)"

Check out this demonstration on JSFiddle.

Answer №2

To capture changes in the $watch function, the first step is to monitor the first attribute. Once it changes, the content of all selected values needs to be extracted and stored in a new array, referred to as firstContent. The second select will display items from the firstContent array. Below is the revised code snippet from the updated JSFiddle:

<select multiple="multiple" ng-model="first" ng-options="c.name for c in listObj">
</select>
<select multiple="multiple" ng-model="second" ng-options="element for element in firstContent">
</select>

$scope.$watch('first', function(value) {
    if (!value) {
        return;
    }
    var firstContent = [];
    for (var i = 0; i < value.length; i++) {
        firstContent = firstContent.concat(value[i].content);
    }
    $scope.firstContent = firstContent;
});

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

Strings within strings within strings - a triple layer of quotes

Here is a snippet of the code that I'm working with: <select class="form-select" id="topicId" name="topicId" onchange="javascript: var data = $(':input[name]', '#dynamic-form'). ...

Eliminate repeat entries in MongoDB database

Within our MongoDB collection, we have identified duplicate revisions pertaining to the same transaction. Our goal is to clean up this collection by retaining only the most recent revision for each transaction. I have devised a script that successfully re ...

I am encountering issues with posting data when my custom class is initialized with a constructor

Here is some C# code that I am having trouble with: public class MeasurementListController : BaseController { readonly MeasurementListService _mlS; public MeasurementListController(MeasurementListService mlS) { _mlS = mlS; } [ ...

Error Type: Property 'history' is not defined and cannot be read

My goal is to automatically redirect the user to the login page when they hit the /logout route. The authentication process works as expected (jwt token is removed), but I'm encountering issues with the app failing to redirect to /login upon logout. ...

Preventing CSRF Errors when activating API endpoints in Node Express JS by ensuring that bypassing the error message with next() function is ineffective

In this middleware block, I have implemented a mechanism to render a 404 page when an invalid CSRF token is detected. /* * Middleware for rendering 404 page on invalid csrf token */ this.app.use((err: any, req: Request, res: ...

Is your Vue.js chart malfunctioning?

I have been experimenting with chart.js and vue.js. The component I created is called MessageGraph, and it is structured like this (with data extracted from the documentation): <template> <canvas id="myChart" width="400" height="400">< ...

An advanced password checker that notifies the user of any spaces in their password

I need help fixing my JavaScript code. The program should prompt the user for a password using a dialogue box, and then validate that the input has no spaces. If a space is detected, the program should stop and display an alert saying "Invalid, contains a ...

Utilizing db.system.js Function within the $where Clause

Here is an illustration of a basic function that I have saved: db.system.js.save({_id: "sum", value: function (x, y) { return x + y; }}); However, when attempting to call it within the $where clause, a Reference not exist error occurs. <?php $collec ...

Double-checked in p:commandButton, encountering a race condition with oncomplete

When I execute the server action using p:commandButton, I then refresh the form to display hidden fields and show a dialog. Attempting to refresh only the panels with hidden buttons yields the same result: After I call dialog.show(), a second refresh is t ...

I am looking for a custom script for a splash page that will automatically redirect users to one of three designated pages based on the information stored

As a programmer, I'm well-versed in coding but lack knowledge about creating and utilizing cookies. If anyone could provide guidance on this matter, it would be highly appreciated. I believe I require two concise scripts for this task. 1st Script: T ...

The issue of calling the child window function from the parent window upon clicking does not seem to be functioning properly on Safari and Chrome

I'm attempting to invoke the function of a child window from the parent window when a click event occurs. Strangely, this code works in Firefox but not in Safari or Chrome. Here is the code snippet I am using: var iframeElem = document.getElementById( ...

simulated xhr server along with the locales in polymer appLocalizeBehavior

Currently, I am in the process of developing a web frontend utilizing Polymer. Within my web component, I incorporate various other components such as paper-input or custom web components. To facilitate testing for demonstration purposes, I have integrated ...

Decoding json data with targeted API keys

Looking for some assistance here. I've got a JSON data set that looks like this: [ { "positive": 2, "negative": 4 }, { "positive": 9, "negative": 18 }, { "positive": 6, "negative": 12 } ...

AngularJS : Resolving Alignment Issues with ng-repeat and ng-include

The ng-repeat feature is being utilized here with an inclusion of a different HTML partial. <div ng-repeat="item in feedItems"> <div ng-include="'item.itemType.html'"> </div> </div> Below is the CSS for the partial H ...

Managing time-intensive web service operations using JavaScript callbacks

One of the operations in my Web application involves a function that returns a value, which then needs to be passed to a web service method running separately from the application. This web service operation takes some time to complete and therefore must r ...

Even after being removed, the input field in Firefox stubbornly maintains a red border

I have a project in progress that requires users to input data on a modal view and save it. The validation process highlights any errors with the following CSS snippet: .erroreEvidenziato { border: 1px solid red; } Here is the HTML code for the moda ...

Step-by-step guide on using nodemon on a web hosting server

I am currently designing a website that includes a login form and I am in the process of uploading it to a web hosting service In order to activate my login form, I have to use node index Is there a way to change the destination of this tag: <li class ...

The constructor for audio in Next JS cannot be found

I'm facing an issue and struggling to find a solution. My project follows the standard structure of Next JS. In the root directory, I have included a components folder. Within the components folder, there is a component with the following code: imp ...

Utilize Meteor's ability to import async functions for seamless integration into method calls

Encountering an issue with this Meteor app where the error TypeError: vinXXX is not a function occurs when attempting to call an exported async function named "vinXXX" from within a method call in a sibling folder, which has been imported in the methods f ...

Transfer responsibilities of events to the canvas and then fetch the Element in the handler

Currently, I am utilizing the Raphaël library to create a network graph, where nodes are depicted as circles. Users have the ability to dynamically add nodes by clicking on the canvas. When a new node is added, an Element object is pushed into both a Set ...