Tony
Tony

Reputation: 12695

AngularJS checkbox & ng-change works very strange

I have an array with items like:

{ 
   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;
}

the problem is, when I click on any chekcbox, the {{x}} renders only true/ false, and the color and name disappears. Why ??

Upvotes: 0

Views: 394

Answers (2)

tpie
tpie

Reputation: 6221

You need to bind x.show to ng-checked and change ng-change to ng-click if all you want to do is flop the value of show. You don't need ng-model.

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

Plunker Demo

Upvotes: 1

sylwester
sylwester

Reputation: 16498

  1. Bind your check box to x.show instead x

  2. You can remove ng-change="changeShow" bit as angular will update show properties

Please see 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>

Upvotes: 2

Related Questions