Updating values within an ng-repeat loop by using the ng-change directive to increment or decrement

Below is an example code snippet that demonstrates a checkbox feature:

<!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>Welcome to LearnKode - A code learning platform</title>
          <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"></script>
    </head>
    <body ng-app="changeExample">
        <div ng-controller="ExampleController">
            <div class="container">
                <div class="col-md-3 well">
                    Are you developer  <input type="checkbox" ng-model="isTrue" ng-change="count=count+1" />
                   Count: {{count}}
                    <pre>{{isTrue}}</pre>
                </div>
            </div>
        </div>
        <script>
        var app = angular.module("changeExample", []);
        app.controller('ExampleController', ['$scope', function ($scope) {
            $scope.isTrue = true;
        }]);
    </script>
    </body>
    </html>

The question at hand is how to modify this code so that the count is only incremented when the checkbox is checked, and decremented when it is unchecked. Any assistance with this would be greatly appreciated.

Answer №1

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
  <title>Welcome to CodeMasters - A platform for mastering coding</title>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"></script>
</head>

<body ng-app="changeExample">
  <div ng-controller="ExampleController">
    <div class="container">
      <div class="col-md-3 well">
        Are you a developer?
        <input type="checkbox" ng-model="isTrue" ng-change="isTrue ? (count=count+1) :(count=count-1) " />Count: {{count}}
        <pre>{{isTrue}}</pre>
      </div>
    </div>
  </div>
  <script>
    var app = angular.module("changeExample", []);
    app.controller('ExampleController', ['$scope',
      function($scope) {
        $scope.isTrue = false;
      }
    ]);
  </script>
</body>

</html>

Feel free to modify the ng-change attribute.

Answer №2

Give this a try and see how it can help you.

<!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>Experience the power of LearnKode - Your go-to platform for mastering code</title>
          <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"></script>
    </head>
    <body ng-app="changeExample">
        <div ng-controller="ExampleController">
            <div class="container">
                <div class="col-md-3 well" ng-repeat="Option in OptionList">
                    Are you {{Option.choice}}  <input type="checkbox" ng-model="Option.value" ng-change="UpdateCount(Option)" />
                   Count: {{Option.count}}
                    <pre>{{Option.isTrue}}</pre>
                </div>
            </div>
        </div>
        <script>
        var app = angular.module("changeExample", []);
        app.controller('ExampleController', ['$scope', function ($scope) {
            $scope.isTrue = false;
$scope.count = 0;
$scope.OptionList = [{
 choice: "Developer",
 value: false,
 count: 0
},{
 choice: "Tester",
 value: false,
 count: 0
},{
 choice: "Lead",
 value: false,
 count: 0
},{
 choice: "Architect",
 value: false,
 count: 0
}
];
$scope.UpdateCount = function(Option){
 if(Option.value){
   Option.count = Option.count + 1;
 }
 else {
  Option.count = Option.count - 1;
 }
}
        }]);
    </script>
    </body>
    </html>

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

Adding data to a multidimensional array in JavaScript

I am in need of creating a multidimensional JavaScript array dynamically, following this specific structure: array_answers[0][1]:"yes" array_answers[1][2]:"no" array_answers[2][2-subquestion]:"text input" array_answers[3][8]:"yes" array_answers[4] ...

Verify if the specified value is present in the dropdown using AngularJS

Utilizing AngularJS, I have implemented an input field with autocomplete functionality. The autocomplete feature pulls data from a JSON file and displays it in a dropdown table format. Users are able to filter the results and select a value from the dropdo ...

Deactivate the button once it's been used | Discord.js version 14

In my index.js, I created a function to respond when a button is pressed and then disable it. client.on("interactionCreate", async (interaction) => { if (interaction.isButton()) { if (interaction.customId === "yes") { co ...

jsp fullcalendar select not functioning properly

The code snippet for the select: function within fullcalendar is as follows: select: function(start, end, jsEvent, view) { if (start.isBefore(moment())) { $('#calendar').fullCalendar('unselect'); return false; } else { //ajax Cal ...

A guide on how to implement promise return in redux actions for react native applications

I'm using redux to handle location data and I need to retrieve it when necessary. Once the location is saved to the state in redux, I want to return a promise because I require that data for my screen. Here are my actions, reducers, store setup, and ...

What is the best method to generate a distinct identifier for individual input fields using either JavaScript or jQuery?

I have attempted to copy the table n number of times using a for loop. Unfortunately, the for loop seems to only work on the first iteration. I am aware that this is due to not having unique IDs assigned to each table. As a beginner, I am unsure how to cre ...

"Learn the process of extracting information from a database and exporting it to a CSV file with Angular 2

Currently, I am facing an issue where I need to retrieve data from a database and export it to a CSV file. While I am able to fetch all the data successfully, I am encountering difficulty when trying to fetch data that is in object format as it shows up as ...

Javascript error when attempting to add leading zeros

Is there a way to utilize JavaScript or JQuery in order to prepend a zero to this script? for (im=1;im<=31;im++){ days[im]=everyDay[im]; } ...

Refresh ng-repeat array after implementing filter in controller

I am currently facing an issue with updating my table view when changing a variable that filters an array. The filter is applied in the controller based on the values of a specific variable called columnFilter. However, the filter does not reapply to updat ...

The pagination feature of the material-ui data grid is experiencing issues with double clicks because of its compatibility with the react-grid-layout library for

I am currently using the react-grid-layout library to manage the resizing of both charts and a material-ui data grid table. However, I am encountering an issue where when clicking on the table pagination arrow, it does not work properly. I have to click tw ...

Creating my website with a unique inverse color scheme

I'm looking to change the color scheme of my webpage so that it is inverse (white becomes black and black becomes white) similar to the Dark Reader chrome extension: https://chrome.google.com/webstore/detail/dark-reader/eimadpbcbfnmbkopoojfekhnkhdbiee ...

Utilizing the "each" function in jQuery to create click events for buttons that are linked to specific paragraphs

Right now, I am facing a situation where I have three buttons, each assigned with an ID that matches their order. Upon clicking a button, the paragraph associated with that order should hide itself using .hide(). My challenge lies in finding out how to ut ...

typescript defining callback parameter type based on callback arguments

function funcOneCustom<T extends boolean = false>(isTrue: T) { type RETURN = T extends true ? string : number; return (isTrue ? "Nice" : 20) as RETURN; } function funcCbCustom<T>(cb: (isTrue: boolean) => T) { const getFirst = () => ...

Switching a conditional className to a styled component

Currently, I am in the process of converting my project from plain CSS to styled components using styled-components. So far, I have successfully converted all of my components except for one. I have looked at various examples on Stack Overflow but none of ...

Refresh only a portion of a page using PHP and JavaScript

I have a webpage set up with multiple sections in separate divs. Currently, the essential divs required are <div id="main">...</div> & <div id="sidebar">...</div> Each div contains PHP code like: <?php include("page.php") ...

What is the best way to mix up the middle letters within certain positions of a word?

Here is what I have managed to achieve so far: mounted() { const randomVariants = [...Array(3)].map(() => this.baseWord .split('') .sort(() => 0.5 - Math.random()) .join('') ) const variantsWithoutIniti ...

Creating a unique Angular JS / Material / Datatables application - Proper script loading sequence required based on page context

My top two declarations placed above the closing body tag. When used in a material dropdown page, the current order of these scripts works fine. However, when I switch to my datatables page (which is a separate page), I need to swap the order of the two s ...

How can I respond with an error HTTP status code in Express utilizing Node.js?

While working on the login page, I encountered an issue with sending credentials from Angular to Express through a GET request. My goal is to have Express send a response if the data is found in the database, which can be handled by Angular. However, if th ...

What is the proper way to implement parameters and dependency injection within a service?

My objective is to achieve the following: (function(){angular.module('app').factory("loadDataForStep",ls); ls.$inject = ['$scope','stepIndex'] function ls ($scope, stepIndex) { if ($routeParams ...

A guide on integrating the MUI Timepicker with the newest 6 version using Formik

I am currently experimenting with the MUI React Timepicker component and facing an issue during integration with Formik for validation. The problem lies in the inability to bind values properly in the initialValues of the form. const [initialValues, setI ...