Search code examples
javascriptangularjsangularjs-scope

AngularJS - Limit increment and decrement


I have two buttons, one is for increment and other for decrement my scope.

I want : Min. number = 0 and Max. number = 50.

I've try this :

myApp.controller('StepCtrl', function($scope, $timeout, $state, $stateParams) {


    $scope.event = {
      priceid: 0,
    }

   if ($scope.event.priceid === 0) {

    console.log("This is 0")

    $scope.nextPrice = function() {
      $scope.event.priceid += 5;
    }

    $scope.previousPrice = function() {
      $scope.event.priceid = 0;
    }     

    } else if ($scope.event.priceid === 50) {

    console.log("This is 50")

    $scope.nextPrice = function() {
      $scope.event.priceid = 50;
    }

    $scope.previousPrice = function() {
      $scope.event.priceid -= 5;
    }

    } else {

    console.log("This is into 0 and 50")

    $scope.nextPrice = function() {
      $scope.event.priceid += 5;
    }

    $scope.previousPrice = function() {
      $scope.event.priceid -= 5;
    }

    }

})

But, I can have value like -40 or 95, I think my "If" and "Else" are ignored.

Have you an idea ?

Thanks for reply. :)


Solution

  • I would have to see your full controller to get the full picture. But I believe the problem is that your expressions are being evaluated once at startup instead of in real-time.

    My solution would be to replace your if-else statement with this.

    $scope.event = {
      priceid: 0,
    }
    
    $scope.nextPrice = function() {
      if($scope.event.priceid < 50)
        $scope.event.priceid += 5;
    }
    
    $scope.previousPrice = function() {
      if($scope.event.priceid > 0)
        $scope.event.priceid -= 5;
    }
    

    This way your condition will be evaluated every time you call $scope.previousPrice() or $scope.nextPrice() instead of those methods just being assigned to at runtime.