1

How can I go about getting checked check box item's ID in a repeated list from a click of a button and add items to a variable / Array for later use?

html:

<input id="btnCheck" type="button" value="Next" ng-click="addSelected()" />    
<div ng-controller="movieController">
        <ul>
            <li ng-repeat="movie in Movies">
                    <input id="chkBox-{{ movie.MovieID }}"
                         type="checkbox"
                         ng-checked="selection.indexOf(movie.MovieID) > -1"
                         ng-click="toggleSelection(movie.MovieID)"
                    />
            </li>
        </ul>
    </div>

Script:

$scope.AddSelected = function () {
    var selected = $scope.selection
    console.log(selected);
}

$scope.selection = [];
$scope.toggleSelection = function toggleSelection(movie) {
    var idx = $scope.selection.indexOf(movie);
    if (idx > -1) {
        $scope.selection.splice(idx, 1);
    }
    else {
        $scope.selection.push(movie);
    }
};
redM
  • 53
  • 5
  • possible duplicate of [How can AngularJS bind to list of checkbox values?](http://stackoverflow.com/questions/14514461/how-can-angularjs-bind-to-list-of-checkbox-values) – dting Apr 29 '15 at 07:28
  • Actually the answer in that post helped me, but not entirely. After the selection has been made, how do I access the $scope.selection values with a click of a button, say console.log it and view the objects or save it in a session variable. Maybe my approach to all this is all wrong. Bare with me guys I'm still really fresh to angular. – redM Apr 29 '15 at 12:15

2 Answers2

0

You can use ng-options for multiple select. More usefull;

<select name="movies" ng-model="selectedMovieIDs" 
ng-options="m.MovieID as m.MovieID for m in movies">

</select>

More more info : ngOptions

hurricane
  • 6,521
  • 2
  • 34
  • 44
0

You could create a custom filter which would return a selected value id, for that you need pass two parameters to filter 1st parameter will perform check, if it is true then 2nd parameter property array will be return from the filter.

Markup

<body ng-app="app">
  <div ng-controller="movieController">
    {{(Movies | returnPropertyWhenCheckedTrue: 'checked' :'MovieID')}}
    <ul>
      <li ng-repeat="m in Movies">
        <input id="chkBox-{{ m.MovieID }}" type="checkbox" ng-model="m.checked"/>
      </li>
    </ul>
  </div>
</body>

Filter

app.filter('returnPropertyWhenCheckedTrue', function() {
  return function(array, propertyToChecked, property) {
    var returnArray = [];
    angular.forEach(array, function(value, index) {
      if (value[propertyToChecked])
        returnArray.push(value[property]);
    });
    return returnArray;
  }
});

Working Plunkr

Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299