The behavior of AngularJS checkbox and ng-change is definitely puzzling

I am facing an issue with my array structure:

{ 
   key : 'abc',
   color: 'Red',
   show: true
}

<div ng-repeat="x in myArray">
    <input type="checkbox" ng-model="x" ng-change="changeShow($index)" checked="checked" />
    <div style="background-color:{{x.color}}; width: 5px;" class="left">&nbsp;</div>
    <label>{{x.key}}</label>
    {{x}}
</div>

$scope.changeShow = function (index) {
    $scope.myArray[index].show = !$scope.myArray[index].show;
}

However, the problem arises when I interact with checkboxes, causing only true/false to render and making the color and name disappear. Why is this happening?

Answer №1

  • Connect your checkbox to x.show instead of just x

  • You can eliminate the ng-change="changeShow" part as Angular will automatically update show properties

Check out the demo below

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

angular.module('app').controller('homeCtrl', homeCtrl);

homeCtrl.inject = ['$scope']

function homeCtrl($scope) {

  $scope.myArray = [{
    key: 'abc',
    color: 'Red',
    show: true
  }]


};
<!DOCTYPE html>
<html ng-app="app">

<head>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>

<body ng-controller="homeCtrl">
  <div ng-repeat="x in myArray">
    <input type="checkbox" ng-model="x.show" checked="checked" />
    <div style="background-color:{{x.color}}; width: 5px;" class="left">&nbsp;</div>
    <label>{{x.key}}</label>
    {{x}}
  </div>
</body>

</html>

Answer №2

If you simply want to toggle the value of show, you can bind x.show to ng-checked and replace ng-change with ng-click. There is no need for ng-model in this scenario.

<input type="checkbox" ng-checked="x.show" ng-click="changeShow($index)" />

Check out this Plunker Demo

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

Display a Popup at 5PM without the need for a page refresh, updating in real-time

After searching extensively online, I was unable to find a suitable solution for my issue. What I am aiming for is to have a popup appear on my page every day at 5:00 PM without the need to refresh the page. If I happen to access the page before 5:00 PM an ...

Unable to display the value of my array in JSON encoded PHP due to it being undefined

In my cart.php file, I have encoded an array to JSON and returned it to an AJAX function: $data = array(); $data['total'] = '10000'; $data['quantity'] = '10'; echo json_encode($data); In my index.php f ...

Executing jQuery when the DOM is loaded in Angularjs

Seeking assistance with integrating jQuery into AngularJS for a project. I am relatively new to AngularJS and experiencing difficulty in firing jQuery on Dom Ready. Despite various attempts, the code does not seem to work as expected. I am currently using ...

Maintaining state value during client-side navigation in NextJs with Next-Redux-Wrapper

Currently, I am working on resolving the hydration issue that occurs when using wrapper.getServerSideProps. The problem arises when I reroute with the existing setup and the store gets cleared out before adding new data. This leads to a blank page as essen ...

Issue with Ajax call not triggering the Controller Action in MVC

I am encountering an issue with making an ajax call to the controller action method that returns a json object. In addition, I need to pass the integer CheckID to the method. Any assistance would be greatly appreciated. Thank you in advance! ***View*** ...

The Web Browser is organizing CSS elements in an alphabetized sequence

map.css({ 'zoom': zoom, 'left': map.width()/(2*zoom) - (point[0]/100)*map.width(), 'top': map.height()/(2*zoom) - (point[1]/100)*map.height() Upon observation, it appears that Chrome adjusts the map zoom first be ...

`Exit function in Vue.js: A step-by-step guide`

Here is a code snippet in vue.js which includes an async function: async up(id, point){ this.change = true const pId = id + '-' + firebase.auth().currentUser.uid db.collection('answer').d ...

Discover multiple keys within a new Map object

Our usual approach involves creating a new Map like this: const hash = new Map() hash.set(key,value) To retrieve the information, we simply use: hash.get(specificKey) An advantage of using Map is that we have flexibility in choosing keys and values. Cur ...

Is there a way to pass asynchronous data to a UI Bootstrap modal in Angular using resolve?

I'm having trouble injecting async data into a UI Bootstrap modal in Angular. The code below shows the controller responsible for opening the modal. import insertOpportunityModal from './insertOpportunityModal.html'; export default class O ...

Parent Directory Injector: Prioritizing Injection of Parent Directories

Currently, I am utilizing 'grunt-injector' to inject a list of files using 'app/**/*.js'. However, I am facing dependency errors due to the alphabetical order in which the files are injected. To avoid these issues, I am looking for a so ...

Tracking the last time an app was run in Javascript can be achieved by creating a variable to store the date when

Exploring the world of Javascript as a newbie, I find myself with index.html, stylesheet.css and div.js in my app. Within div.js lies a code that magically generates a schedule for our team members over 2 weeks. However, there's a catch - consistency ...

`Hovering over a div triggers a continuous animation loop`

I've gone through various questions and solutions related to this issue, but unfortunately, none of them seem to work for me. It's possible that I might be overlooking something or my scenario is slightly unique. The main problem I'm facing ...

Having trouble with updating your website asynchronously through code? In need of a detailed explanation?

Here are two Javascript functions that are used to call a python file in order to update an HTML page. The first function works perfectly fine, but the second one seems to be malfunctioning without throwing any errors. function button(key) { var xhttp ...

Watch for changes in a nested collection in Angular using $scope.$watch

Within my Angular application, there is a checkbox list that is dynamically generated using nested ng-repeat loops. Here is an example of the code: <div ng-repeat="type in boundaryPartners"> <div class="row"> <div class="col-xs- ...

Create a fresh trail underneath the overlay image

When utilizing fabric.js to draw a new path with isDrawingMode: true enabled (seen on the right side of the screenshot), I am encountering an issue where the path appears above my overlay image, which is a transparent png. https://i.stack.imgur.com/R3fGn. ...

Is the statement true in JavaScript if either true or true or false?

I have implemented this code snippet to prevent my page from being iframed: window.onload = function(){ try { if (window.parent && window.parent.location.hostname !== "app.herokuapp.com"){ throw new Error(); } catch (e){ //do something ...

The token 'x.id' came out of nowhere - instead, [x.id}})] should have been expected in column 11 of the expression [elimina({{x.id}})]

Encountering an error: Error: [$parse:syntax] Syntax Error: Token 'x.id' is unexpected, expecting [:] at column 11 of the expression [elimina({{x.id}})] starting at [x.id}})]. This is the code snippet causing the issue: <tr ng-repeat="x i ...

Exploring the World of Angular JS Services

Following the recommended practices, I am working on encapsulating my global functions into reusable factory services. In the provided code snippet, my objective is to execute a function that takes the string value of "Qprogress" from my JSON data, perform ...

"Troubleshooting the ineffectiveness of JavaScript's

(After reviewing all questions and answers related to this issue, I have not found a solution that works for me.) Here is the code snippet in question: var timeoutHandle; function showLoader(show) { if (show) { $('.loader').html(&a ...

javascript mobile nav event

My website utilizes a bootstrap feature for mobile devices where a left sidebar pops up when clicking a button. I am not very familiar with bootstrap, but I would like to link a javascript event to determine if the left sidebar is visible. How can I achiev ...