1

I have the following $scope.watch function:

$scope.logChecked = []; 
$scope.selectAll = false;
$scope.$watch('selectAll', function(selectAll) {
       console.log($scope.logChecked.length, $scope.logChecked, selectAll);
});

The console.log() output correctly enumerates $scope.logChecked while $scope.logChecked.length shows 0

0 [pf2n1448: false, cc7a1340: false, cc7a1328: false, pf2n1424: false, if2n1328: false…] true

I am modifying logsChecked with the following checkbox:

<td><input type="checkbox" ng-model="logChecked[log.batchId]"/></td>

What's going on here?

3
  • please show how you are modifying logsChecked Commented Sep 21, 2015 at 12:21
  • you haven't actually resized the array. Commented Sep 21, 2015 at 12:28
  • Also, I'm not sure why the downvote. Thanks to @DanielA.White, I realized that I needed to expound a bit on my question.
    – JSK NS
    Commented Sep 21, 2015 at 12:31

1 Answer 1

1

Because logChecked is an array with nothing inside (hence length is 0), but you attached properties to it (arrays are still objects).

var foo = [];

foo.bar = 'baz';

document.write(foo.length); // 0

document.write(foo.bar); // "baz"

The part that isn't obvious is that log.batchId isn't numeric. Thus logChecked[log.batchId] attaches that value as a property of logChecked, but not inside the array.

Your problem could be solved by making logChecked an object ({}) instead. To get the number of things in that object, use Object.keys($scope.logChecked).length

Not the answer you're looking for? Browse other questions tagged or ask your own question.