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

Having trouble deploying a Heroku app using Hyper? Here's a step-by-step guide to

After running the following commands: https://i.stack.imgur.com/WZN35.png I encountered the following errors: error: src refspec main does not match any error: failed to push some refs to 'https://git.heroku.com/young-brook-98064.git' Can anyon ...

Top solution for efficiently capturing and storing user input in a React JS application: Event Handler

I've recently designed an input field for inputting details of items. In order to effectively capture and save the entered information, which of the following event handlers would be most suitable? onClick onChange onLoad onKeyPress ...

Is there a way to remove a post with AngularJS and Express?

In my post.serv.js file, I have a code snippet for the function "delete" in my controller. "use strict"; app.factory('JnttPost', function ($resource) { var PostResource = $resource('/api/post/:_id', { _id: "@id" }, { ...

Having issues with Vue.js and the splice method not functioning properly on an array row

Having an Object array, I noticed that when I try to remove an object from the array list, only items are deleted from the end. <div class="hours" v-for="(time, index) in hour" :key="index"> So, I decided to place a cli ...

I am requesting for the average to be adjusted based on the user's choice between Hindi or English percentage scale

Currently, the average is being calculated in the HTML code. When a user input is changed, the average breaks. What can be done to update the average for each individual person? Controller var app = angular.module('myApp', []); app.controller( ...

Issue encountered: Unforeseen command: POST karma

Whenever I try to run my test cases, I encounter the following error message: Error: Unexpected request: POST data/json/api.json it("should $watch value", function(){ var request = '/data/json/api.json'; $httpBackend.expectPOST(reque ...

Fade out a component in Material UI/React by setting a timeout in the parent's useEffect hook for when it unmounts

Incorporating a fade out transition into my child component, <Welcome />, using Material UI's Fade component is my current goal. This transition should be triggered by two specific conditions: The timeout set in the useEffect function expires. ...

Issues with displaying images in CSS when using HTML 5 canvas drawing

In attempting to draw an image on a canvas using a pre-loaded image and CSS, such as: img.style.backgroundColor="red"; ctx.drawImage(img,0,0,100,100); I have observed that the image is drawn without incorporating the CSS modifications. Are HTML canvases ...

I attempted various methods but was unable to successfully call the webmethod in the code behind using jQuery Ajax and Knockout

I have attempted various solutions, such as enabling friendly URL resolution and utilizing web method with session enabled, but unfortunately, the issue remains unresolved. I kindly request your assistance in resolving this matter. Here is my HTML code for ...

The GM_xmlHttpRequest POST method is not functioning properly when called within an event listener

My simple goal is to intercept xmlHttpRequests sent by a page and send them to my local server for logging in a text file. However, Ajax calls do not work in event listeners. I have tried various solutions all day long without success. Here is the code sni ...

The transition from Vuetify3's VSimpleTable to VTable is ineffective and unsuccessful

The v-simple-table component has been renamed to v-table Old code that was using v-simple-table may not work correctly after the renaming. It is recommended to use v-data-table with the same data, as it works correctly. Here's the full page code: Yo ...

Visual Studio encountered an issue while attempting to debug on the web server. The remote server has denied access with error code 403, indicating that debugging is currently

How can I successfully run my application from IIS on my local machine? I've created the virtual directory and added the application to it. The application runs properly when launched from IIS, but I encounter errors when trying to run it through VS 2 ...

Styling with CSS and JavaScript: The ultimate method for desaturating multiple images

I am currently designing a portfolio website that will feature desaturated thumbnails of all my work. When you hover over each thumbnail, the color will fade in and out upon mouseover. Since this page will include numerous thumbnails, I have been contempl ...

Increase the dimensions of the jQuery modal confirmation box

I am working on a jQuery confirmation dialog that displays some details for the user. My goal is to have the dialog adjust its dimensions after the user clicks "YES" to show a smaller text like "Please wait...". How can I dynamically change the size of the ...

An issue arose while attempting to pin a file on IPFS: A TypeError [ERR_INVALID_ARG_TYPE] was encountered, specifying that the argument "url" must be a string data type

Adding the files to another project resulted in an error that I am struggling to understand. When running "node scripts1/runScript.js", the error message received is as follows: Error occurred while pinning file to IPFS: TypeError [ERR_INVALID_ARG_TYPE]: ...

Tips on retrieving values from input files using jQuery

Is there a way to retrieve the value of an input type using jQuery? Specifically, when I add a file to the input file, I want to dynamically add more input types with the file's value. Currently, I am using the following code: $('#show_input&apo ...

Steps to retrieve the latest value of a specific cell within the Material UI Data Grid

After updating the cell within the data grid, I encountered an issue where I could retrieve the ID and field using the prop selectedCellParams, but retrieving the modified value was proving to be challenging. In order to successfully execute the PUT reque ...

`Uniform background color across all pages`

My goal is to allow customers to select a color that will persist across different pages on the website. The code below shows how users can choose a color on the first page: <select id="color" style="width: 5%; height: 10%" size="5"> ...

Having trouble with a basic jQuery selector not functioning as expected

Having trouble parsing this HTML code: <tr id="a"> <td class="classA"> <span class="classB">Toronto</span> </td> <td class="classC"> <span class="classD">Winnipeg</span> </ ...

When deploying, an error is occurring where variables and objects are becoming undefined

I've hit a roadblock while deploying my project on Vercel due to an issue with prerendering. It seems like prerendering is causing my variables/objects to be undefined, which I will later receive from users. Attached below is the screenshot of the bui ...