Pregunta

I've got a simple upVote/downVote counter. It works great on the downvote, but when you click upvote it appends a 1 onto the end of the original upvote variable. (it Doesn't add, it Appends) but only for the upvote. Why is this and how can I fix it?

<span>
<a ng-click="upCount = upCount + 1" ng-init="upCount=location.upVoteCount" 
class="btn btn-success">{{upCount}}
</a>

<a ng-click="downCount = downCount - 1" ng-init="downCount=location.downVoteCount" 
class="btn btn-danger">{{downCount}}
</a>
</span>

Note: both location.upVoteCount and location.downVoteCount are defined as integers. They are populated using ng-repeat="location in locationList". So their values are not explicitly declared in the controller. Changing the + to a - works just fine, the add function also works if you replace location.upVoteCount (or location.downVoteCount) with a number.

Thanks for your help!

¿Fue útil?

Solución 3

I'm not sure why you're having a problem unless the location entity has strings on it. I just did a quick fiddle and it works fine. Here's the HTML:

<div ng-app="myApp" ng-controller="myController">
    <span>
<a ng-click="upCount = upCount + 1" href="#" ng-init="upCount=location.upVoteCount">Up: {{upCount}}</a>
<a ng-click="downCount = downCount - 1" href="#" ng-init="downCount=location.downVoteCount">Down: {{downCount}}</a>
</span>
</div>

Here's the JavaScript:

var app = angular.module("myApp", []);

app.controller("myController", function($scope) {
    $scope.location = {
        upVoteCount: 0,
        downVoteCount: 0
    };
});

It works just fine up or down voting. Run it here:

http://jsfiddle.net/jeremylikness/bPQXJ/

Otros consejos

+ means both "add" and "concatenate" while - means "minus".

Force the variables to operate in addition mode:

upCount = (parseInt(upCount) + 1)

Try this

<a ng-click="upCount = upCount + 1" ng-init="upCount=parseInt(location.upVoteCount)" 
class="btn btn-success">{{upCount}}
</a>

<a ng-click="downCount = downCount - 1" ng-init="downCount=parseInt(location.downVoteCount)" 
class="btn btn-danger">{{downCount}}
</a>

Update

If your location.upVoteCount and location.downVoteCount variables aren't integers/numbers then this might be an issue.

Try parsing then first. See ng-init directive above.

I'm not in a position to try it out right now, but how about:

ng-click="upCount = upCount - (-1)"

No + operators to confuse the expression evaluator

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top