<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script data-semver="1.5.0" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.js"></script>
<script data-semver="1.5.0" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular-resource.js"></script>
<link href="style.css" rel="stylesheet" />
<script src="script.js"></script>
</head>
<body>
<h1>AngularJS - Data binding a true/false value to a checkbox </h1>
<div>
Notice when you click the checkboxes, the JSON below changes too.
That shows that the underlying model is changing.
</div>
<div ng-controller="PersonCtrl">
<h2>Teens - checkboxes bound to model, click and underlying model changes</h2>
<table>
<tr>
<th>Name</th>
<th>Birthday</th>
<th>Happy?</th>
</tr>
<tr ng-repeat="teen in teens"
ng-class="{'happy': teen.happy, 'sad': !teen.happy}">
<td>{{teen.name}}</td>
<td>{{teen.birthday}}</td>
<td><input type="checkbox" ng-model="teen.happy"/></td>
</tr>
</table>
<h2>Here is the raw JSON from the controller</h2>
<pre>{{ teens | json }}</pre>
</div>
</body>
</html>
// Instantiate the app, the 'myApp' parameter must match what is in ng-app
angular.module('myApp', ['ngResource'])
.factory('Teen', Teen)
.controller('PersonCtrl', PersonCtrl);
/**
* Teen is a service that calls a local .json file teens.json
* The query method is added to allow returning an array of multiple Teen objects
*/
function Teen($resource) {
return $resource('teens.json');
}
// Create the controller, the 'PersonCtrl' parameter must match an ng-controller directive
function PersonCtrl($scope, Teen) {
// Teens are from static json file
$scope.teens = Teen.query();
}
body {
font-size: 24px;
}
.happy {
background-color: green;
}
.sad {
background-color: red;
}
[
{
"name": "Teen One",
"birthday": "1/1/2001",
"happy": true
},
{
"name": "Teen Two",
"birthday": "2/2/2001",
"happy": true
},
{
"name": "Teen Three",
"birthday": "3/3/2001",
"happy": false
}
]