问题描述
我目前正在使用angular-google-maps构建具有几种不同标记类型的地图。 在我的地图下方,我有一组简单的复选框,如下所示:
<div class="mapOptions">
<form action="" class="form-inline" style="text-align:center">
<label for="">General:</label>
<input type="checkbox" checked value="Games">
<label for="" style="color:#000033">Games</label>
<input type="checkbox" checked value="Practices">
<label for="" style="color:#ffd900">Practices</label>
</form>
</div>
在我的控制器中,我初始化了空数组,然后通过对我的API端点的调用用“标记”填充它们:
vm.markersGames = [];
vm.markersPractices = [];
我想做的是在未选中复选框的情况下清除每个数组(例如:用户取消选中“游戏”,控制器中的方法设置vm.markersGames = []
),并在单击复选框时重新填充每个数组(例如:User检查“ Practices”,我的控制器内的方法将调用API端点并填充vm.markersPractices
)。
我遇到的问题是不知道如何在input
s中正确添加“检查/取消检查处理程序”。
选中后尝试重新加载标记:
vm.checkToggle = function(isChecked, value) {
if (!isChecked) {
vm[value] = [];
} else {
getPlayerAddress();
$scope.$apply();
}
};
getPlayerAddress()
调用API来填充标记数组。
1楼
您可以使用ngChange指令来侦听输入的更改。
这是一个例子:
控制者
(function(){
function Controller($scope, Service) {
//Object to know if the input is checked or not
$scope.form = {};
$scope.markersGames = [];
$scope.markersPractices = [];
//isChecked : input checked or not
//value : keyname of your array, for example markersGames
$scope.change = function(isChecked, value){
!isChecked
//If input is not checked, set our $scope[value] to empty array
? $scope[value] = []
//If the input is checked, call Service
: Service.get(value).then(function(data){
//Retrieve and set data
$scope[value] = data;
});
}
}
angular
.module('app', [])
.controller('ctrl', Controller);
})();
然后,您可以使用带有承诺的服务提出您的请求
服务
(function(){
function Service($q){
function get(url){
var defer = $q.defer();
var promise = defer.promise;
if (url === 'markersGames') {
defer.resolve([1,2,3,4]);
} else {
defer.resolve([4,6,8,1,5,2]);
}
return promise;
}
var factory = {
get: get
};
return factory;
}
angular
.module('app')
.factory('Service', Service);
})();
然后,您可以在html中添加ngChange指令:
的HTML
<body ng-app="app" ng-controller="ctrl">
<form action="" class="form-inline" style="text-align:center">
<label for="">General:</label>
<input type="checkbox" checked value="Games" ng-model="form.game" ng-change="change(form.game, 'markersGames')">
<label for="" style="color:#000033">Games</label>
<input type="checkbox" checked value="Practices" ng-model="form.practice" ng-change="change(form.practice, 'markersPractices')">
<label for="" style="color:#ffd900">Practices</label>
</form>
{{markersGames}}
{{markersPractices}}
</body>