【发布时间】:2015-11-28 05:32:55
【问题描述】:
我无法让复选框显示模型的正确状态(选中/未选中)。我的控制器中有以下内容:
app.controller('PhotosCtrl', ['$scope', function($scope) {
$scope.form = {};
$scope.editPhotos = {
token: $scope.token,
idArray: $scope.idArray
};
}]);
我的表单如下所示:
<form accept-charset="UTF-8" name="editPhotosForm" ng-submit="submit(editPhotos);" multipart="true" novalidate>
<input name="utf8" type="hidden" value="✓">
<input name="authenticity_token" type="hidden" ng-model="editPhotos.token" ng-init="editPhotos.token='<%= form_authenticity_token %>'">
<div class="results-label"><b>{{total_count}}</b> <span ng-if="total_count == 1">Photo</span><span ng-if="total_count != 1">Photos</span> Found</div>
<div>
<div class="col">
<a ng-repeat="r in results" class="card result-link">
<div class="content result">
<div class="caption">
<input type="checkbox" ng-model="idArray[r.id]">
</div>
<div class="image-container" ng-style="{'background-image': 'url(' + r.image_url + ')'}">
</div>
</div>
</a>
</div>
</div>
</form>
在我的转发器元素上,我调用ng-init="idArray[r.id] = 'false'" 来为r 中的每个项目初始化一个键r.id = 'false'。我不知道我是否需要这样做。我已经尝试了没有它的代码,它没有任何区别。我也尝试过使用ng-value-true 和ng-value-false,但它们似乎对我不起作用。
我在这个问题上看到的大多数其他帖子都处理简单的变量(例如$scope.someVar = true,而不是像哈希这样的更复杂的结构。
这是idArray的结构:
$scope.idArray = {1290: "false", 1291: "true", 1292: "true", 1293: "false", 1294: "false", 1414: "false"};
这是由我的转发器中的ng-init 生成的,因为事先无法知道照片的 ID。
这是results 的样子:
{
id: 1290,
company_id: null,
image_url: "http://s3.amazonaws.com/mybucket/photos/images/000/001/290/original/214.JPG?1432217895"
}
【问题讨论】:
-
您预计会发生什么,而会发生什么?没有要迭代的
results数组,儿子,我看不到您如何看到任何复选框。而且您将字符串'false'与布尔值false混淆了。 -
在我的转发器中,我将哈希键初始化为
'false'而不是false,因为ng-true-value和ng-false-value的值始终是字符串。results数组是通过 AJAX 调用在$scope上定义的,该调用返回数据库中的照片列表。我将idArray的结构添加到我上面的问题中以供参考。 -
在阅读我的答案时,我发现我的答案可能存在问题,具体取决于您的对象
result的数据结构。可以发个样品吗? -
我刚刚在我的问题上附加了一个 sn-p。
-
你的结果是这个对象的数组?
标签: angularjs checkbox angular-ngmodel