【发布时间】:2016-05-18 11:47:59
【问题描述】:
这会导致将相同的项目添加到数组中 - 用于查询 - 可能两次。当模式关闭并再次打开并且不使用过滤时,一切都很好(这是因为我的模式只是在 HTML 中,我只是在点击时隐藏它们)。当一个已经被添加的项目,但是它的复选标记由于过滤而丢失时,再次检查两个相同的项目被添加。当未选中时,两者都被删除,除非它是数组中的最后一项,否则无法删除(我知道这是我的草率逻辑)。下面是相关的 HTML 和 JavaScript 代码(著名的遗言)。
HTML:
<div style="display: inline-block;" ng-controller="modalCtrl">
<button ng-click="showModal = !showModal">Entities</button>
<div ng-init="showModal=false">
<div class="modal fade in" aria-hidden="false"
style="display: block;" ng-show="showModal">
<div class="modal-dialog">
<div class="modal-content">
<strong>ENTITIES</strong>
<div>
<div>
<input type="text" placeholder="Search" ng-model="simpleFilter">
<button type="button" ng-click="showModal=false">Ok</button>
</div>
</div>
<br>
<div ng-repeat="entity in entityArray | filter:simpleFilter">
<label> <input
style="display: inline-block; margin-top: 5px"
type="checkbox" ng-model="entityChecked"
ng-change="getEntityFromModal(entity, entityChecked)" /> <a>{{entity}}</a>
</label>
</div>
</div>
</div>
</div>
</div>
</div>
模态控制器:
angular.module("app").controller("modalCtrl", ["$scope", "shareDataService", "getDataService", function ($scope, shareDataService, ngDialog, getDataService) {
$scope.entityArray = shareDataService.getEntityArray();
$scope.depotArray = shareDataService.getDepotArray();
$scope.getEntityFromModal = function (entity, checked) {
shareDataService.setModalEntity(entity, checked);
};
$scope.getDepotFromModal = function (depot, checked) {
shareDataService.setModalDepot(depot, checked);
};
}]);
shareDataService(相关方法):
angular.module("app").factory("shareDataService", function () {
var entityArrayService = [];
var depotArrayService = [];
var modalEntity = [];
var modalDepot = [];
getEntityArray: function () {
return entityArrayService;
},
getDepotArray: function () {
return depotArrayService;
},
setModalEntity: function (entity, checked) {
if (!checked) {
for (var i = 0; i < modalEntity.length; i++) {
if (modalEntity[i] === entity) {
modalEntity.splice(i, 1);
}
}
} else {
modalEntity.push(entity);
}
},
setModalDepot: function (depot, checked) {
if (!checked) {
for (var i = 0; i < modalDepot.length; i++) {
if (modalDepot[i] === depot) {
modalDepot.splice(i, 1);
}
}
} else {
modalDepot.push(depot);
}
},
});
在我的主控制器中调用数据服务方法时还有其他实例,但这些仅用于数组的长度。所以如果复选框问题解决了,一切都解决了。
【问题讨论】:
-
对于要保留的复选框,您需要保存到模型中。角度过滤时,它会为转发器创建一个子范围,并且您的数据可能会在此过程中被删除。
-
感谢您的意见,如果 SoluableNonagon 的答案明天有效(回到工作岗位),我不会打扰这个笨蛋,如果不是我会的。
-
@SatejS 因为下面的答案不起作用 - 这是一个 plunker - plnkr.co/edit/2ptIAdOyaIw8mGqpU7Cp?p=preview 。重要的是,您必须按照以下步骤查看问题。 1)使用搜索栏搜索数字“11” 2)选中“11”旁边的复选框 3)删除搜索“11”并输入搜索“22”。 4) “22”旁边的复选框 5) 从搜索中删除“22”。然后,您将看到 11 保留在数组中(在页面底部输出),但在过滤列表后未选中其复选框。
标签: javascript html angularjs checkbox angularjs-ng-repeat