raneshu raneshu - 1 year ago 238
Javascript Question

angular view not updating when checkbox clicked

View not updating when checkbox is checked. Should I used $scope.$apply?
I need the

Current state
to change between YES and NO depending on whether the checkbox is checked or not. Here's the code on JSbin

<!DOCTYPE html>
<html ng-app="notesApp">
<title>Notes App</title></head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.8/angular.js"></script>
<body ng-controller="MainCtrl as ctrl">
<h2>What are your favorite sports?</h2>
<div ng-repeat="sport in ctrl.sports">
<label ng-bind="sport.label"></label>

<input type="checkbox"

Current state: {{sport.selected}}


And here's the JS:

angular.module('notesApp', [])
.controller('MainCtrl', [function() {
var self = this;
self.sports = [
{label: 'Basketball', selected: 'YES'},
{label: 'Cricket', selected: 'NO'},
{label: 'Soccer', selected: 'NO'},
{label: 'Swimming', selected: 'YES'}


Answer Source

You need to add quotations because it's an angularjs expression and it also needs to be a constant. If YES is used for an angular expression normally angular would look for a scope variable named YES, but that's not going to be a constant angular expression as the value of YES could change.

Instead you want to just set the value to 'Yes' as you want to assign the value as the constant string 'YES'. If you looked in the console you would have seen: Expected constant expression for 'ngTrueValue', but saw 'YES'.

<input type="checkbox"