angular 单击复选框时视图未更新

angular view not updating when checkbox clicked

选中复选框后视图未更新。我应该使用 $scope.$apply 吗? 我需要 Current state 根据复选框是否被选中在 YES 和 NO 之间切换。 Here's JSbin 上的代码

<!DOCTYPE html>
<html ng-app="notesApp">
  <head>
    <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">
     <div>
       <h2>What are your favorite sports?</h2>
       <div ng-repeat="sport in ctrl.sports">
         <br/>
         <label ng-bind="sport.label"></label>

         <div>
           <input type="checkbox"
           ng-model="sport.selected"
           ng-true-value="YES"
           ng-false-value="NO">
         </div>


         <div>
           Current state: {{sport.selected}}
         </div>

       </div>
    </div>
  </body>
</html>


这是 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'}
   ];

}]);

你需要添加引号,因为它是一个 angularjs 表达式,而且它还需要是一个常量。如果 YES 用于 angular 表达式,通常 angular 会查找名为 YES 的作用域变量,但它不会是常量 angular 表达式,因为 YES 的值可能会改变。

相反,您只想将值设置为 'Yes',因为您希望将值分配为常量字符串 'YES'。如果您查看控制台,您会看到:Expected constant expression for 'ngTrueValue', but saw 'YES'.

<input type="checkbox"
           ng-model="sport.selected"
           ng-true-value="'YES'"
           ng-false-value="'NO'"/>

http://plnkr.co/edit/ehXObXaXicC1BvKyQtmI?p=preview

参考 angularjs 的错误参考文档中的 constexpr。它说

Some attributes used in conjunction with ngModel (such as ngTrueValue or ngFalseValue) will only accept constant expressions.