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?
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.
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
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?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.