I am trying to change the function of this AngularJS Example that syncs (Using <input type="checkbox">
) to return an array of objects.
In my html I have the following code using ng-repeat and some function calls from the AngularJS demo example:
<div ng-repeat="item in items" class="standard" flex="50">
<label> <input type="checkbox" ng-checked="exists(item, selected)" /> {{item.name}} </label>
</div>
I also have a button to select or remove all checkbox entries:
<label> <input type="checkbox" ng-checked="isChecked()" ng-click="toggleAll()" autofocus ng-model="checkbox" ng-change='delayedSearch(0)'/>
<span ng-if="!isChecked()">all</span>
<span ng-if="isChecked()">nothing</span>
</label> <br><br>
In my controller I initialize array items as follows:
$scope.items = [{name:'K://',value:'nemo'},{name:'Bugzilla',value:'bugzilla'},{name:'Jira',value:'jira'}];
and the corresponding functions to interact with the checkboxes:
$scope.toggle = function (item, list) {
var idx = list.indexOf(item);
if (idx > -1) {
list.splice(idx, 1);
if (list.length == 0){
list.push('nothing');
}
}else {
var id = list.indexOf('nothing');
if (id > -1) {
list.splice(id,1);
}
list.push(item);
}
};
$scope.exists = function (item, list) {
return list.indexOf(item) > -1;
};
$scope.isChecked = function() {
return $scope.selected.length === $scope.items.length;
};
$scope.toggleAll = function() {
if ($scope.selected.length === $scope.items.length) {
$scope.selected = ['nothing'];
} else if ($scope.selected.length === 0 || $scope.selected.length > 0) {
$scope.selected = $scope.items.slice();
}
};
Currently my code returns a list of objects of all checked items, for example:
[{"name":"K://","value":"nemo"},{"name":"Bugzilla","value":"bugzilla"},{"name":"Jira","value":"jira"}]
I would like to get a list of only the values of all items that are checked like this:
["nemo","bugzilla","jira"]
You can map results list like this:
var valuesArray = [{"name":"K://","value":"nemo"},{"name":"Bugzilla","value":"bugzilla"},{"name":"Jira","value":"jira"}].map(function(obj) {
return obj.value;
}); // ["nemo","bugzilla","jira"]