1

So I am new to both AngularJS and CoffeeScript. I am trying out some simple examples and the one that I am trying to do is to display the count of number of checkboxes selected

and here is the Javascript for that

$scope.$watch('results', function(results){
$scope.count = 0;
angular.forEach(results, function(result){
  if(result.selected){
    $scope.count += 1;
  }
})
}, true);

This works perfectly fine. Now I am trying to do the same thing in coffeescript and here is what I have

$scope.$watch 'results', (results) ->
  $scope.count = 0;
  ( $scope.count += 1 if result.selected ) for result in $scope.results

There are no compilation errors in the above coffeescript but nothing happens when I select or deselect the checkboxes.

Any ideas?

3 Answers 3

0

Your use of for in syntax is correct but you forgot the 3rd argument:

$scope.$watch 'results', (results) ->
  $scope.count = 0;
  ( $scope.count += 1 if result.selected ) for result in $scope.results
, true

Look how I pass to $watch a third argument true. It makes a deep check of the collection values instead of just checking reference equality.


If you only need a shallow watch you should use $watchCollection (angular >=1.2):

$scope.$watchCollection 'results', (results) ->
  $scope.count = 0;
  ( $scope.count += 1 if result.selected ) for result in $scope.results

This one is compiled 100% exactly to the javascript snippet you provided:

$scope.$watch "results", (results) ->
  $scope.count = 0
  angular.forEach results, (result) ->
    $scope.count += 1  if result.selected
    return
  return
, true

I use return explicitly if I don't need to return anything
Check this: Is there any way to not return something using CoffeeScript?

Sign up to request clarification or add additional context in comments.

Comments

0

This is the compiled coffeescript:

$scope.$watch('results', function(results) {
  var result, _i, _len, _ref, _results;
  $scope.count = 0;
  _ref = $scope.results;
  _results = [];
  for (_i = 0, _len = _ref.length; _i < _len; _i++) {
    result = _ref[_i];
    _results.push(result.selected ? $scope.count += 1 : void 0);
  }
  return _results;
});

Which is not the same functionality as the JavaScript example you have above.

Comments

0

You can go to js2coffee for converting javascript to coffeescript and vice versa.
This is the result, which I believe it should do what you want:

$scope.$watch "results", ((results) ->
  $scope.count = 0
  angular.forEach results, (result) ->
    $scope.count += 1  if result.selected
), true

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.