Sebastian Lagua
Sebastian Lagua

Reputation: 390

How to increment my value in angular js?

Hello guys i have some question about $scope and json parse with angular.

I have function they send to api +1 when someone click on like. Easy like count. But when i trying Increment this value: where my mistake? Angular just concatenate value +1 Example i have 6 when i click they show 61 again click 611

<button class="place-button col-33" ng-if="usermeta.like_post" ng-click="like(post.id); post.likes =  post.likes + 1">
     <span class="col-50">
          <i class="fa fa-beer"></i>
     </span>
     <span class="col-50">
         {{likes}}
     </span>
</button>

This how i get my pot from controller and service

PostService.getPost(postId).then(function(data) {
     scope.post = data.post;
})

When i try this without get data from Json API it's work but with them no!

Upvotes: 1

Views: 548

Answers (3)

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48367

Try to use this: $scope.likes= + $scope.likes+1;. This force result to integer.

HTML

<div ng-app>
   <div ng-controller="TodoCtrl">
     <button ng-click="incrementLikes()">
      Click
     </button>
     {{likes}}
   </div>
</div>

JS

function TodoCtrl($scope) {
   $scope.likes='0';
   $scope.incrementLikes=function(){
      $scope.likes=+$scope.likes+1;
   }
}

function TodoCtrl($scope) {
  $scope.likes='0';
  $scope.incrementLikes=function(){
     $scope.likes=+$scope.likes+1;
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.17/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div ng-app>
  <div ng-controller="TodoCtrl">
    <button ng-click="incrementLikes()">
    Click
    </button>
    {{likes}}
  </div>
</div>

Upvotes: 3

Alexander Kravets
Alexander Kravets

Reputation: 4395

Looks like you service returns post.likes as a string instead of number, something like this: { likes: "6" }. That's why the string concatenation is happening instead of increment.

To fix this:

-you could change the service to return the likes as a number: { likes: 6 }, or

-convert the likes at the frontend this way:

PostService.getPost(postId)
    .then(function(data){
        $scope.post = data.post;
        $scope.post.likes = parseInt($scope.post.likes);
})

Upvotes: 2

Kishan Mundha
Kishan Mundha

Reputation: 3141

It treating your model value post.likes as string. Use parseInt(post.likes) + 1 or Number(post.likes) + 1. These function not accessible in ui, so use function inside controller and call that function in ui.

$scope.incrementlike = function() {
    $scope.post.likes = parseInt($scope.post.likes) + 1;
}

Upvotes: 0

Related Questions