简体   繁体   中英

How to find the difference between two numbers in angular.js?

I want to find the difference between two numbers in anuglar js directive tags.

      <div ng-repeat="post in posts | orderBy:'-upvotes'">
    <span class="glyphicon glyphicon-thumbs-up"
      ng-click="incrementUpvotes(post)"></span>
    {{post.upvotes}}
     <span class="glyphicon glyphicon-thumbs-down"
      ng-click="incrementDownvotes(post)"></span>
    {{post.downvotes}}


    <span class="glyphicon glyphicon-glyphicon-minus"></span>
    <span class="glyphicon glyphicon-glyphicon-plus"></span>
      {{post.upvotes - post.downvotes}}  // I want the difference of these two numbers

There has to be a way to do this using the absolute value of the two numbers, or using some angular method to find the difference between them. Currently with the above code it will execute the equation, but it does strict subtraction, not giving me the actual difference between these numbers.

Add something like this to your post definition (in the model)

...
// assuming you have these already (or similar)
post.upvotes = 2;
post.downvotes = 1;
...
// add something along the lines of
post.voteDiff = function(){
  return Math.abs(upvotes - downvotes);  // would return 1 in this case
}

Then in your HTML could would simply call it like any other attribute {{post.voteDiff()}}

UPDATED

Thanks to @New Dev for the correction in the comments

{{post.upvotes + post.downvotes}}

This solved the problem. Don't need any fancy math or methods.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM