2013-04-27 67 views
16

我浏览过类似的问题几个小时,但没有拿出任何完全匹配的东西。我想要做的是有一个复选框通过数据绑定自动检查数据中的真/假值。我可以获取项目名称来加载没有问题,我甚至可以稍后将复选框值保存到服务器,但我无法获得正确加载的初始值。如何让复选框在我的数据模型中绑定到布尔值?

下面是一个简化的例子,显示了基本问题; HTML:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script> 
<script src="shoppingListNg.js"></script> 
<body ng-app> 
<div ng-controller="ShoppingListCtrl"> 
    <table> 
     <tr ng-repeat="item in shoppingList"> 
      <td> 
       <div>{{item.text}}</div> 
      </td> 
      <td> 
       <input type="checkbox" ng-model="item.isGotten" /> 
      </td> 
     </tr> 
    </table> 
</div> 
</body> 

而这里的Java脚本:

function ShoppingListCtrl($scope) { 
    $scope.shoppingList = [ 
     { 
     "text": "V8 fusion", 
     "isGotten": "true" 
     }, 
     { 
     "text": "Whole milk container", 
     "isGotten": "false" 
     }, 
     { 
     "text": "Protein bars", 
     "isGotten": "true" 
     } 
    ]; 
}; 

任何想法,为什么我不能让这些复选框尊重模型中的“真”与“假”的价值观?当页面加载时,它们始终显示未选中状态。我是否需要使用ng检查或不同的指令?

回答

17

问题在于引号中有“true”和“false”,这使得它们成为字符串,而不是Angular可以绑定复选框的布尔值。

如果您只删除引号如下,您的代码将正常工作。一个工作示例是http://plnkr.co/edit/gkchmOBTkBtVv3TijlZW

function ShoppingListCtrl($scope) { 
    $scope.shoppingList = [ 
     { 
     "text": "V8 fusion", 
     "isGotten": true 
     }, 
     { 
     "text": "Whole milk container", 
     "isGotten": false 
     }, 
     { 
     "text": "Protein bars", 
     "isGotten": true 
     } 
    ]; 
}; 
+0

但是,这不适用于单选按钮你知道如何做单选按钮 – Xvegas 2015-05-14 21:11:54

7

根据您的数据,您可能不希望在代码中使用纯正/错误。 AngularJS将true/false和1/0布尔变换为字符串,所以你最好使用字符串。

在此codepen中,我使用“1”和“0”作为布尔值,ngTrueValue和ngFalseValue告诉AngularJS如何保持绑定完好无损。非常简单和干净。

Codepen这里:http://codepen.io/paulbhartzog/pen/kBhzn

代码片段:

<p ng-repeat="item in list1" class="item" id="{{item.id}}"> 
    <strong>{{item.id}}</strong> <input name='obj1_data' type="checkbox" ng-model="list1[$index].data" ng-true-value="1" ng-false-value="0"> Click this to change data value below 
</p> 
<pre>{{list1 | json}}</pre>