[英]Populate/clear array when checkbox checked/unchecked
我目前正在使用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來填充標記數組。
您可以使用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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.