Preserve the data from various select boxes using their respective ids

I am facing an issue with handling select boxes within an ng-repeat loop in my AngularJS application. Each object has one or more select boxes, and the user needs to select 3 priorities from these boxes and save them by clicking a button. In the save function, I need to access both the object's id to which the select box belongs and the selected value.

Below is the current code snippet with my concerns and queries highlighted in the comments:

HTML

<div ng-repeat="object in objects">
    <div>
        <md-input-container>
            <md-select ng-model="selectedPriority" placeholder="Priority">
                <md-option ng-value="{{ priority.name }}+{{ object.id }}" ng-repeat="priority in priorities">{{ priority.name }}</md-option> <!-- I am facing an error while setting ng-value. How can I resolve this?-->
            </md-select>
        </md-input-container><br>
        {{ object.id}}
    </div>
</div>
<md-button ng-click="save()">Save</md-button>

Controller

$scope.save = function () {
    console.log($scope.selectedPriority); // I expect to retrieve all object ids with their selected values, but it shows undefined
}

@Sajeetharan: The object JSON is structured as follows:

JSON

[{  
    "date":"2017-01-21T18:20:00.873Z",
    "duration":120,
    "location":"Test",
    "passed":false,
    "id":"58838763019ac0479455bbc0"
},
{  
    "date":"2017-01-21T15:15:00.420Z",
    "duration":10,
    "location":"Test",
    "passed":false,
    "id":"58839ac9019ac0479455bbc1"
}
//...]

Answer №1

Here is a helpful tip:

Start by initializing selectedPriority as an empty array:

$scope.selectedPriority = [ ];

Utilize ng-change to update selectedPriority with changes, so that you can access them in the save function later on.

<div ng-repeat="object in objects">
    <div>
        <md-input-container>

            <md-select ng-model="selectedPriority[$index].priority" placeholder="Priority" ng-change=" selectedPriority[$index].objectId = object.id">
                <md-option ng-value="priority.name" ng-repeat="priority in priorities">{{ priority.name }}</md-option> <!--I'm experiencing an error when setting ng-value. How can I resolve this?-->
            </md-select>
        </md-input-container><br>
        {{ object.id}}
    </div>
</div>
<md-button ng-click="save()">Save</md-button>

Next, you can access selectedPriority within the save function:

$scope.save = function(){
    // access $scope.selectedPriority[neededIndex].objectId ;
    // access $scope.selectedPriority[neededIndex].priority ;
}

Answer №2

A different approach is needed, avoid using it like this:

ng-value="{{ priority.name }}+{{ object.id }}"

Instead, separate them:

ng-model="object.selectedPriority"
and ng-value="priority". Finally, when the save button is clicked, create a loop to display each object's selected priority.

It is assumed that your priorities array consists of objects with keys named name. You can refer to this: http://codepen.io/anon/pen/pRPbdq

Please forgive any misunderstandings :)

Answer №3

Thankfully, the ng-model directive allows you to pass an array, but the key is to utilize the correct index.

Make the following changes to your HTML:

<div ng-repeat="item in items track by $index">
  <div>
    <select ng-model="selectedItem[$index]">
      <option ng-repeat="option in options" value="{{ option.value }}+{{ item.id }}">{{option.label}}</option>
    </select>
  </div>
</div>

Here, we're utilizing a scope variable called selectedItem, which is initialized as an array.

By simply logging $scope.selectedItem on button click, you will see an array containing the desired values.

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

A guide on creating a Javascript leap year algorithm using Test-Driven Development techniques

Currently, I am working on crafting a leap year algorithm by utilizing a TDD suite. This marks my initial venture into the realm of TDD. Displayed below is the code extracted from the spec file. var Year = require('./leap'); describe('Lea ...

Can you explain the compatibility between comet and PHP?

As I utilize Comet iframe, I simply send script tags from the backend PHP file to the frontend where JavaScript displays them. I would appreciate it if someone could provide a concise explanation of how the comet server fits into the equation and how comm ...

I have my doubts about whether I am implementing the recapcha API correctly in a React application

I implemented the recapcha API in order to prevent bots from submitting posts on a forum site. As a new developer, I'm not sure if this is a real threat or not, as the users are limited to a maximum of 3 posts before they have to pay for more. I' ...

Why isn't the show/hide feature in Jquery functioning properly?

I have a div that needs to be displayed after hovering over another element. These elements are not within the same div. The popup info should appear when an icon with the class .option_36_124 is hovered over. $(".option_36_124").hover(function(){ $(& ...

How to programmatically update one input value in AngularJS and trigger validation as if it was manually entered by the user?

I'm currently using Angular 1.3.0rc2 and facing an issue with setting one input field based on another input field after the blur event. When I try to set the value of an input field that only has a synchronous validator, everything works fine by usi ...

Putting Text Inside a Video Player in HTML

Is there a way to insert text, like a Logo, into my video player? https://i.sstatic.net/CZ6Rp.png I would appreciate any help on how to achieve this. Thank you. <video width="320" height="240" controls src="video/flashtrailer.mp4"> Your browser ...

Leveraging Json data in Angular components through parsing

I am currently developing an angular application where I need to retrieve and process data from JSON in two different steps. To start, I have a JSON structure that is alphabetically sorted as follows: { "1": "Andy", "2": &qu ...

Iterate over an array of objects to showcase the property values within an HTML tag using JavaScript

I am a beginner in JavaScript and I am currently working on an exercise. My goal is to iterate through an array of objects within another object, map the index values from one object to the id values in another object, and based on that, perform a certain ...

The PHP AJAX call is returning an undefined response status

I'm facing two issues here. The first problem is that when I try to access response.status, it returns undefined. The second issue is related to the creation of "$_SESSION['promo-code'] = $arr". When I enter a promo code, I encounter the fol ...

How to pass props dynamically to components in VueJS with ease

My view is always changing: <div id="myview"> <div :is="currentComponent"></div> </div> I have linked it to a Vue instance: new Vue ({ data: function () { return { currentComponent: 'myComponent', } ...

Selecting a event from Google Places Autocomplete using a mouse click

I have successfully implemented Google's autocomplete API as per the documentation. However, I am facing an issue with a form that is submitted via Ajax every time it changes. The problem arises when using the autocomplete feature for location selecti ...

Monitor and adjust variables simultaneously using AngularJS

My goal is to dynamically calculate and display values based on two other variables in real time. I've successfully managed to track one variable, but not both simultaneously. $scope.color_slider_bar = { value:0, minValue: 0, maxValue: ...

How can you use ng-click to disable a div in AngularJS?

I'm looking to dynamically disable a div in AngularJS based on a certain condition. I know I can achieve this by adjusting the CSS (such as reducing contrast and color) but the div also has an ng-click property that I want to prevent from being trigge ...

Unable to locate module: Issue: Unable to locate 'exports'

Looking to make the switch from RequireJS 2.2 to Webpack 3 for my Angular 1.5 app, I aim to establish a Webpack environment that can accommodate existing RequireJS code while transitioning gradually to Webpack and ES6. The plan is to write tests, refactor ...

Sending the returned value back to the previous view in Ionic

I'm working on creating a form with a unique setup: The main view displays a list of all fields to be filled out, such as 1. Merchant, 2. Amount, 3. Date Instead of a multi-step form, here's what I'm aiming to do: Click on the Merchant f ...

Guide to importing an AngularJS controller into an Express file (routes.js)

Currently, I am in the process of developing a restful service and my goal is to organize my callbacks within controllers in order to avoid cluttering my routes.js file. Previously, I had been using controller = require(path.to.controller); This enabled ...

Is there a way to automatically play videos without any audio?

Is there a way for my video to automatically start playing when the page loads, without sound? I want it to function similar to the video on this webpage: . I've experimented with various jQuery, JavaScript, and CSS techniques from online resources, ...

HTML counterpart to PHP's include for JavaScript components

I am searching for a Javascript alternative to a method I have been using in PHP. Specifically, I want to streamline the basic setup of my pages: <!DOCTYPE html> <html lang="en"> <head> <meta ch ...

Execute the npm run build command to build the Angular app using Gradle task

I am working on an Angular 1 application. After running npm run build I also need to initiate a Gradle task. Is there a way to automate this process? ...

In PATCH requests, JSON data is not transmitted through Ajax

I'm attempting to send JSON data from the client to my server with the following code: $.ajax({ url : 'http://127.0.0.1:8001/api/v1/pulse/7/', data : data, type : 'PATCH', contentType : 'application/json' ...