WirJun WirJun - 27 days ago 7
AngularJS Question

ngRepeat Array of Objects and corresponding functions

I am trying to change the function of this Angluar Example Synching (

Using <input type="checkbox">
) to an array of objects

In my html I have the followning lines using ng-repeat and some function calls from the angular 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 so select or remove all checkbox entries in my html:

<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 initialzie array items as follows:

$scope.items = [{name:'K://',value:'nemo'},{name:'Bugzilla',value:'bugzilla'},{name:'Jira',value:'jira'}];


and the corresponding functions to mark on/off all checkboxes (toggle all), to mark on/off just one checkbox (toggle), isChecked and Exists.

$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();
}
};


Current result: It returns a list objects of all Entries that are checked, like

[{"name":"K://","value":"nemo"},{"name":"Bugzilla","value":"bugzilla"},{"name":"Jira","value":"jira"}]


What I would like to get is a list values of all Entries that are checked, like

["nemo","bugzilla","jira"]


Any ideas?

Answer Source

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"]