hugo der hungrige
hugo der hungrige

Reputation: 12912

How to use checkboxes for creating an array-list of related objects in angularjs

I have a given array of objects, whose objects I would like to add to a 'selected'-list depending on related checkboxes. How could I set them up without having to set up the controller to much.

Here is the fiddle which works fine, when using radio-boxes instead: http://jsfiddle.net/JohannesJo/6ru2R/

JavaScript:

app = angular.module('app',[]);

app.controller('controller', function($scope){
$scope.aData = [
    {i:1},
    {i:2}
];
$scope.aSelected = [];
});

html:

<body ng-app="app">
        <div ng-controller='controller'>
            <input type = "checkbox" ng-model = "aSelected"  value = "{{aData[0]}}">
            <input type = "checkbox" ng-model = "aSelected"  value = "{{aData[1]}}">

            <div>test:     {{oSelected}}</div>
         </div>
</body>

Upvotes: 0

Views: 806

Answers (1)

bmleite
bmleite

Reputation: 26870

One option is to watch for changes on the oSelected Array and create the list of related objects base on it.

$scope.$watch(function () {
    return $scope.oSelected;
}, function (value) {
    $scope.selectedItems = [];
    angular.forEach($scope.oSelected, function (v, k) {
        v && $scope.selectedItems.push($scope.aData[k]);
    });
}, true);

jsfiddle: http://jsfiddle.net/bmleite/zea7g/2/

Upvotes: 2

Related Questions