Angular: Empty Fiddle
http://angularjs.org/
by boneskull
HTML
<script src="http://code.angularjs.org/angular-1.0.1.js"></script>
<div ng-controller="MyCtrl">
<table>
<tr ng-repeat="value in values">
<td><input type="checkbox" ng-model="$parent.selectedValues" checkbox-array="value"/></td>
<td>{{value.name}}</td>
</tr>
</table>
<pre>
{{selectedValues}}
</pre>
<button ng-click="trim()">trim</button>
</div>
JavaScript
var myApp = angular.module('myApp', []);
//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});
function MyCtrl($scope) {
$scope.values = [{
name: 'foo'},
{
name: 'bar'},
{
name: 'baz'}];
$scope.trim = function() {
$scope.selectedValues.pop();
};
}
myApp.directive('checkboxArray', function($parse) {
return {
require: 'ngModel',
link: function(scope, elm, attrs, ngModel) {
var value = scope.$eval(attrs.checkboxArray),
// the thing we will put in our array specified by ngModel
array = $parse(attrs.ngModel); // getter/setter for ngModel
// if we have not defined the ngModel, let's assign an empty array to it
// otherwise we may run into problems getting the length of an undefined object
if (angular.isUndefined(array(scope))) {
array.assign(scope, []);
}
// when the checkbox is clicked, execute this
elm.bind('change', function() {
var arrayValues = array(scope),
// get the actual array out of the scope
i = arrayValues.length;
if (elm.attr('checked')) {
// if we wound up checked, push the thing onto the array specified by ngModel
arrayValues.push(value);
// need to apply since this is a jQuery event
scope.$apply(function() {
ngModel.$setViewValue(true); // checkbox will want to be true/false
array.assign(scope, arrayValues); // update the scope
});
} else {
// find the object in our array and remove it
while (i--) {
if (arrayValues[i] === value) {
arrayValues.splice(i, 1);
...