What is the best way to implement ng-change within an ng-repeat?

My goal is to trigger a function every time a check box is clicked in ng-change. I am looking for a way to determine the value of the model or identify which checkbox was clicked, so that I can call another function based on the checked value. Additionally, I need to handle when a checkbox is unchecked to hide certain values.

I'm not completely confident if my current approach is correct, but here's the code snippet: plunker

HTML

 <input type="checkbox" ng-model="data.model" ng-change="onChnage()" class='checkbox'>

JS

$scope.onChnage = function(){
    if($scope.index == true){
        $scope.indexonClick();
    } else if($scope.aggs == true){
        $scope.aggsonClick();
    } else if($scope.index == false){
        console.log('false');
    }
};

$scope.indexonClick = function(){
    alert('index Clicked!');
}

$scope.aggsonClick = function(){
    alert('aggs Clicked!');
};

Answer №1

Take a look at this code snippet:

// Check out the code snippet below

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  

  $scope.tableData = [{
    name: 'Index',
    url: '#',
    valueMain: 12,
    tValue: 13,
    model: 'index',
    subvalues: [{
      name: 'Keys',
      url: '#',
      valueSub: 544,
      tValue: 67
    }, {
      name: 'Leaders',
      url: '#',
      valueSub: 67,
      tValue: 89
    }]
  }, {
    name: 'Aggregators',
    url: '#',
    valueMain: 78,
    tValue: 91,
    model: 'aggs',
    subvalues: [{
      name: 'TPM',
      url: '#',
      valueSub: 11,
      tValue: 13
    }, {
      name: 'Pollster',
      url: '#',
      valueSub: 23,
      tValue: 45
    }]

  }];
  
  
  $scope.onChnage = function(value,test){
    console.log(test)
    if(value.model=='index'){
      $scope.indexonClick(test)
    } else if(value.model=='aggs'){
      $scope.aggsonClick(test)
    } else if($scope.index==false){
      console.log('false')
    }
  };
  
  $scope.indexonClick= function(test){
    var value = (test == true ? 'clicked' : 'un clicked')
    alert('index ' + value)
  }
  
  $scope.aggsonClick = function(test){
    var value = (test == true ? 'clicked' : 'un clicked')
     alert('aggs ' + value)
  };
});
<!DOCTYPE html>
<html ng-app="plunker">

<head>
  <meta charset="utf-8" />
  <title>AngularJS Plunker</title>
  <script>
    document.write('<base href="' + document.location + '" />');
  </script>
  <link rel="stylesheet" href="style.css" />
  <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5938373e2c35382b77332a1968776a7721">[email protected]</a>" src="https://code.angularjs.org/1.3.20/angular.js" data-semver="1.3.20"></script>
  <script src="script.js"></script>
</head>

<body ng-controller="MainCtrl">
  <table class='table'>
    <thead>
      <tr>
         
        <th>name</th>
        <th>itemOne</th>
        <th>itemTwo</th>
        <th>model</th>
      </tr>
    </thead>
    <tbody ng-repeat="value in tableData| orderBy:'-valueMain'">
      <tr>
       
        <td>
          <button ng-show="value.expand" ng-click='value.expand = false'>-</button>
          <button ng-show="!value.expand" ng-click='value.expand = true'>+</button>
          <input type="checkbox" ng-model="test" ng-change="onChnage(value,test)" class='checkbox'
>
          <a rel="noopener" target="_blank" href={{value.url}}>
{{value.name}}
</a>
        </td>
        <td>{{value.valueMain}}</td>
        <td>{{value.tValue}}</td>
        <td>{{value.model}}</td>
        <tr>
          <tr ng-show="value.expand" ng-repeat="subs in value.subvalues| orderBy:'-valueSub'" >
            <td>
              {{subs.name}}
            </td>
            <td>
              {{subs.valueSub}}
            </td>
            <td>
              {{subs.tValue}}
            </td>
             
          </tr>
        </tr>

      </tr>
    </tbody>
  </table>
</body>

</html>

Please execute this code snippet to see results

You can view the plunker here

Answer №2

Update the function to accept the row as an argument:

... ng-change="onChange(data)" ...

Then, utilize the given row for information:

$scope.onChange = function(row){
  alert(row.name); // Aggregators or Index
};

Check out this Plunkr link. Also, consider using console.log instead of alert.

Answer №3

To properly handle the value, ensure that you pass it into your onChnage() function. Here is an example:

<input ... ng-change="onChnage(data.value)" ... />

It's important to note that you are now passing the current value of the input to the onchange function.

$scope.onChnage = function(value){
    console.log(value);

    ...
};

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

Testing React Hook Form always returns false for the "isValid" property

When creating a registration modal screen, I encountered an issue with the isValid value when submitting the form. In my local environment (launched by npm start), the isValid value functions correctly without any issues. However, during unit testing us ...

Loading external JSON and images located beyond the root directory

Currently, I am attempting to load a JSON file and a set of images from a directory located above my root directory. Although the code I have works, I believe there may be a more efficient way to achieve this. $.getJSON("http://localhost/folder1/folder2/f ...

Troubleshooting module not being found with rekuire, requirish, or rfr in resolving relative require problem in nodejs

Looking to steer clear of the complicated relative path problem detailed here by opting for one of the suggested solutions. I've found three similar libraries that could help: rekuire node-rfr aka Require from Root requirish I've experimented ...

Error: The function res.getHeader is not recognized within the Next.js API environment

I am currently working on a web application using NextJS 13, TypeScript, Next Auth v4, Prisma (using SQLite for development), and OpenAI. While accessing the API endpoint, I encountered an error in the console with the following message: error - TypeError ...

Issue with updating input value during keyup event in Android Chrome specifically

Check out this straightforward jsfiddle: https://jsfiddle.net/gq9jga4q/33/ <input type="text" id="kbdhook" /> <div id="result" >1: </div> <div id="result2" >2: </div> <div id="result3" >3: </div> $('#kbdh ...

Prevent carousel from rotating while video is playing in Bootstrap 4

Currently, I am in the process of constructing a Bootstrap 4 carousel featuring various videos and other content. My goal is to have the carousel pause when a video is playing (with auto-play enabled) and resume once the video reaches its conclusion. I&ap ...

execute the function once the filereader has completed reading the files

submitTCtoDB(updateTagForm:any){ for(let i=0;i<this.selectedFileList.length;i++){ let file=this.selectedFileList[i]; this.readFile(file, function(selectedFileList) { this.submitTC(updateTagForm,selectedFileList); }); } } } ...

When accessing a method exposed in Angular2 from an external application, the binding changes are lost

In my code, I have a method that is made public and accessible through the window object. This method interacts with a Component and updates a variable in the template. However, even after changing the value of the variable, the *ngIf() directive does not ...

Errors occur when utilizing VSTS Web Deploy Arguments

Currently in the process of deploying an Angular JS app using web deploy on VSTS. In order to target a specific path on the Azure app service, I am aiming for /home/site/ to be the deployment location for all project files. If this path is not explicitly ...

Image uploading using AJAX onchange event

Is it possible to use AJAX to upload images when using the input onchange event? I've attempted various methods but none of them seem to be working. Here is the code I am currently using: $(document).ready(function (e) { $("#uploadForm").on(&apos ...

How to display an [object HTMLElement] using Angular

Imagine you have a dynamically created variable in HTML and you want to print it out with the new HTML syntax. However, you are unsure of how to do so. If you tried printing the variable directly in the HTML, it would simply display as text. This is the ...

show content with ajax and php

I am attempting a simple task with ajax, but it's not working as expected. All I want is to display some text when the input button is clicked. ajax.js jQuery(document).ready(function($) { $('#insertForm').change(function(){ // Retrieve th ...

Calculating the Distance Between Elements within a Flex Container Using JavaScript

I am looking to calculate the margin left and right for children of a flex item <div class="sec images" style="display:flex;justify-content:space-between"> <img src="images/en_mb-mega-01.png" alt=""> ...

Eavesdrop on the import function in Node.js

I have a unit test where I need to confirm if the SUT makes a call to require with a specific parameter. The module under test has the following implementation: module.exports = function () { require('foo'); }; Now, I am trying to create a te ...

PhpStorm's error detection for JavaScript syntax does not work in .php files

Currently utilizing PhpStorm 10.0.3 and encountering an issue with JavaScript syntax error detection in the test.php file. It seems that if there are any errors in the JavaScript code, they are not being displayed. For instance: image.setAttribute("data ...

Ways to access the state of a child component in React using React Hooks

What is the most effective solution for accessing a child's state in React using hooks? I have experimented with multiple methods, and below is the one I ultimately settled on. Parent Form export const Form: FunctionComponent<IProps> = ({ on ...

Ensuring Consistent Data in Web Forms When Editing a User's "Points" Field

In the process of creating a booking system, I am faced with an issue regarding how points are allocated to users. An admin can assign points to a user through a form, which the user then uses when booking a slot. The problem arises when the admin opens th ...

Can the combination of a JavaScript frontend and NodeJS backend function effectively together in this scenario?

I have a Domain-A that serves as a static site on Netlify, offering shopping cart functionalities. On the other hand, I have Domain-B hosting a backend server running a Node.JS payment system and utilizing Auth Services through passport.js. Due to its na ...

Error: The function RFB is not defined

Trying to set up a VNC client using AngularJS (tutorial link here), but encountering an error while running the application: TypeError: RFB is not a function Below is the server.js code snippet: var RFB = require('rfb2'), io = require(&apos ...

The for loop does not cycle through every element

I'm working on a class project that involves creating custom HTML tags with JavaScript. I have a for loop set up to iterate over each use of the tag, but for some reason, it only seems to loop over every other tag. I'm specifically trying to crea ...