How to update a boolean value in a JSON object using AngularJS?

Trying to modify a boolean value when a user clicks on a JSON-populated table row. Here's an example of the setup...

$scope.prices = {
"Prices": [
    {
        "Code": "edl",
        "Selected": false
    },
    {
        "Code": "ead",
        "Selected": false
    }
]
}

This data is then connected to a table...

<table>
<tr ng-click="change(item.code)" ng-repeat="item in prices">
    <td>{{prices.Code}}</td> 
    </tr>
</table>

Once a user clicks a row, the change function is triggered to toggle the selected value between true and false.

$scope.change = function (itemCode) {
//update the clicked code selcted value to True/False
// check the current value and switch
// Apologies for the confusion!
if(!$scope.prices.code.selected){
    $scope.prices.code.selected = true
} else {
    $scope.prices.code.selected = false
}
};

Seeking guidance on how to make this work within the change function. Any other approaches would be appreciated! Thank you

Answer №1

Initially, it is illogical to add an additional level in $scope.prices before reaching the actual array of prices.

In simpler terms, instead of:

$scope.prices = {
"Prices": [
    {
        "Code": "edl",
        "Selected": false
    },
    // etc.
]
};

You should directly have the array like this:

$scope.prices = [
    {
        "Code": "edl",
        "Selected": false
    },
    // etc
];

This way, you can easily bind to it:

<table>
    <tr ng-click="change(item)" ng-repeat="item in prices">
        <td>{{item.Code}}</td> 
    </tr>
</table>

Moreover, since $scope.change() now receives the entire item instead of just the code, you can directly toggle its Selected property:

$scope.change = function (item) {
    item.Selected = !item.Selected;
};

Answer №2

Before we proceed, there are a few key adjustments that need to be made.

  1. Make sure to reference the array Prices within the $scope.prices object.

  2. Modify the change() function to accept the reference to the clicked item.

    <table>
      <tr ng-click="change(item)" ng-repeat="item in prices.Prices">
        <td>{{item.Code}}</td>
      </tr>
    </table>
    

    Next step is to implement the change function

    $scope.change = function (item) {
      if (item.Selected) {
        item.Selected = false;
      } else {
        item.Selected = true;
      }
    };
    

Answer №3

If you want a cleaner solution without relying on functions, here's an alternative approach that doesn't require removing functions from $scope to be mindful of memory usage.

<table>
    <tr ng-click="item.Selected = !item.Selected" ng-repeat="item in prices">
        <td>{{item.Code}}</td>
    </tr>
</table>

Have a fantastic day assisting others!

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

Encountering issues while attempting to execute node-sass using npm

Currently, I'm attempting to execute node-sass using npm. Displayed below is my package.json: { "name": "my-project", "version": "1.0.0", "description": "Website", "main": "index.js", "scripts": { "sass": "node-sass -w scss/ -o dist ...

Is there a way to reverse the animation playback in Angular?

I am working on an animation that involves a box fading from its original color to yellow. However, I would like to achieve the opposite effect: when the page loads, I want the box to start off as yellow and then fade back to its original color. The challe ...

Display a particular element when hovered over

Is there a way to make only individual elements pop up on hover instead of all of them at once? items: [{ item: "Book", info: "Lorem ipsum", displayInfo: false }, { item: "Pen", info: "Lorem ipsum", displayInfo: false }, ...

Enhancing the appearance of list options in Autocomplete Material UI by utilizing the renderOption feature

I'm putting in a lot of effort to customize the option elements in the autocomplete list. My plan is to achieve this using the renderOptions prop, where I can create DOM elements and easily apply styles with sx or styled components. However, somethin ...

Changing the color of a selected list element using an Angular directive

I'm currently facing an issue with my directive that is supposed to turn a list element red when clicked. It works fine, but I also want it to revert back to black when another list item is selected, so only one item stays in red color. Here is how I ...

Storing JSON array values as variables using the Linkedin PHP library

I am new to working with APIs and JSON and would really appreciate any assistance on the following. Currently, I am utilizing the PHP Linkedin Library for executing People Queries. Below is the relevant code snippet: <?php $OBJ_linkedin-&g ...

Updating and writing JSON values in Python3

As a newcomer to Python writing, I've hit a stumbling block. My goal is to update the information in the example JSON file below: { "data1": { "info1": [ { "keyA1": "valueA1", "keyA2": "valueA2" }, { "k ...

My Javascript file is not being recognized by MVC

Initially, I created an MVC application without fully understanding that MVC is more backend-oriented than frontend-focused. I ended up building a simple website with just HTML, CSS, and Javascript files, which worked perfectly. However, when I tried to in ...

Issue with converting string to Date object using Safari browser

I need to generate a JavaScript date object from a specific string format. String format: yyyy,mm,dd Here is my code snippet: var oDate = new Date('2013,10,07'); console.log(oDate); While Chrome, IE, and FF display the correct date, Safari s ...

Show a loading progress image during the page loading process (not during form submission)

Is there a way to show a loading GIF image while a page is loading or during postbacks using jQuery and JavaScript for long running tasks or processes that take a significant amount of time to execute? I attempted a solution but the loading image is not d ...

The content is not wrapped when transferred from App.js through props, although it is being wrapped in other scenarios

As I work on developing a basic invoice generator application, I encounter an issue with overflowing content in the "notes" section when passing data through props from the App.js file. Instead of wrapping the text, it overflows its container. import "./Ap ...

Creating a basic JSON array using the push method

When adding comments to a blog post using the line: blogpost.comments.push({ username: "fred", comment: "Great"}); The JSON structure of the comments section will look like this: "comments":[{"0":{"username":"jim","comment":"Good",},"1":{"username":"fre ...

Linking an element's class to the focus of another element in Angular

In my Angular application, I have multiple rows of elements that are wrapped with the myelement directive (which is a wrapper for the input tag). To highlight or focus on one of these elements at a time, I apply the .selected class in the styles. Everythi ...

Angular 7's URL updates, but no other actions take place

I am new to posting here and feeling quite desperate. Currently, I am working with Angular 7 and facing an issue. The problem arises when I manually enter the desired URL, everything works perfectly. However, when I use RouterLink by clicking a button, the ...

Error: A TypeError occurred with the startup because it was unable to read the property 'Collection' as it was

Recently, I encountered a series of problems one after another. The first issue was: TypeError [CLIENT_MISSING_INTENTS]: Valid intents must be provided for the Client To resolve this problem, I made changes to my code from: const Discord = require(" ...

sending information from a PHP form to a JavaScript window

Currently, I am in the process of developing a game using javascript and jquery. In this game, when a player interacts with another character, it triggers the opening of text from an external file using the window.open('') function. At the start ...

Clicking on Only One Card in Material UI React

I've encountered an issue with my code: const useStyles = makeStyles({ card: { maxWidth: 345, }, media: { height: 140, }, }); export default function AlbumCard(props) { const classes = useStyles(); let ...

Issue: Unable to access API target map in AGM using Google Map API

I attempted to integrate a Google map with multiple locations. While I was successful in using an Iframe for one location, I struggled to implement multiple locations within the Iframe. As a result, I tried utilizing AGM and used the same APIKey that I ha ...

Having trouble applying CSS styles to an element using JavaScript

Hello, I have an unordered list with some list elements and I am trying to apply a CSS style to highlight the selected list element. However, the style is not taking effect as expected. function HighlightSelectedElement(ctrl) { var list = document.ge ...

Adding text with jQuery

Currently, I am utilizing the Jquery text editor plugin known as JqueryTE. While adding some functions to it, I have encountered a roadblock. Specifically, I am attempting to insert additional text into the source of the textarea but have been unsuccessfu ...