我是 AngularJS 的新手,不得不接管其他人的项目,该项目几乎没有文档。
我的应用程序中有两种复选框,一种是“全选”复选框,另一种是设备选择复选框。顾名思义,全选将选择它下面列出的所有设备,如果我取消选中“全选”复选框,我可以单独检查设备以查看它们。
这是全选复选框的代码 -
<input type="checkbox" data-ng-model='devCtrl.uiChoices.selectAll' value='true' data-ng-change="devCtrl.selectAll()"/><h4>Select / Deselect All</h4>
Controller :
_this.uiChoices.selectAll = true;
我可以从上面了解到,默认情况下,全选被选中,我可以看到它下面的所有设备也被选中。
移动到设备复选框 -
<input type="checkbox" data-ng-model='device.draw' data-ng-change="device = devCtrl.adjustVisibility(device)" />
Controller -
_this.adjustVisibility = function(draw) {
draw.marker.setVisible(draw.plot);
return draw;
}
基本上,无论何时选择设备,它都会出现在谷歌地图上。如果未选中,它将不会显示在 map 上。
我的问题是,在我取消选中“全选”复选框然后仅选择下面列表中的 2 台设备并刷新页面后,我希望禁用全选并仅显示要选中的 2 台设备并显示在 map 上。
设备列表正在从 MySQL 数据库中提取并动态更新。
感谢任何帮助。
最佳答案
正如我所说,您可以通过 3 种不同的方式来完成。
1 - 使用 $scope 变量
在 AngularJS 中,您有一个主 Controller ,通常设置在 index.HTML 主体中,您可以从所有其他 Controller 访问它。您可以使用它将数据存储在 $scope 变量上。看例子:
index.html:
<body ng-controller="DefaultController">
DefaultController.js:
angular.module('YourModule').controller('DefaultController', ['$scope', function ($scope) {
//Storing Your data
$scope.isChecked = true;
}]);
你的CheckBoxController.js
angular.module('YourModule').controller('YourCheckBoxController', ['$scope', function ($scope) {
//Here you gonna access the $scope variable, that does not change on page reload
$scope.accessingTheVariable= function () {
if ($scope.isChecked) {
//Select All
}
else {
//Do not Select All
}
};
$scope.onCheckBoxToggle {
$scope.isChecked = _this.uiChoices.selectAll;
//More code
};
}]);
2- 使用本地存储
//The property exists
if (localStorage.hasOwnProperty("isChecked")) {
if(localStorage.isChecked) {
//Select All
}
else {
//Do not Select All
}
}
//To set localStorage.isChecked
localStorage.setItem("isChecked", _this.uiChoices.selectAll);
3 - Angular 服务(工厂)
在这种情况下,您应该创建一个可以从项目中的每个 Controller 访问的服务(如果您要在多个 Controller 上使用数据,这很有用)。看:
YourService.js
angular.module('YouModule').factory('YouService', function () {
var data =
{
IsChecked = true
};
data.buildIsChecked = function (isChecked) {
this.IsChecked = isChecked;
};
return data;
});
YourIsCheckedController.js:
angular.module('YourModule').controller('YourCheckBoxController',
['$scope', 'YouService', function ($scope, YouService) {
//Setting the service
//...
YouService.buildIsChecked(_this.uiChoices.selectAll);
//Accessing the service Information (it could be accessed from any Controller, just remember to set Service Name at begin of the module declaration)
var isChecked = MenuService.IsChecked;
}]);
关于javascript - 在页面刷新 AngularJS 后保持复选框被选中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39127400/