0

I need help understanding why my counter doesn't work.

I need a badge to increment/decrement every time I click. When the increment/decrement is done and i pass that counter to my scope badge, i get undefined. But if i add a static number it works.

 app.factory('badgeCounter', function ($log) {

  var items=0;
  var num;

  return {
    countItems: function () {
      ++items;
      $log.info('items: ' + items);
      return items;
    },
    removeItems: function () {
      items--;
      $log.info('items: ' + items);
    },
    listItems: function (items) {
      $log.info('total de items:=> ' + items);
      //return alert(items);
      return items;
    },
    cleanItems: function () {
      return items = 0;
    }
  }

Every time i make an increment, I call the function to see if the increment worked.

badgeCounter.countItems();
badgeCounter.listItems();

It works. But if set it to scope, I don't get the total increment. Can someone tell me what i'm doing wrong and help me?

$scope.items = badgeCounter.listItems();

<div ng-controller = "basketProductController">    
  <span> 
     <button  ng-click="openBasket()" ng-init="items" class="button button-icon ion-ios-cart-outline">
      <span class="badge badge-assertive header-badge"></span>
     </button>
  </span>
</div>
CodeWarrior
  • 2,721
  • 3
  • 18
  • 18
Mr_mufy
  • 11
  • 1
  • 4

1 Answers1

0

Remove the items argument in the listItems function signature.

Change

listItems: function (items) {

to

listItems: function () {

Explanation

Having the items argument in the method signature would mean that within the listItems function, the variable name items will refer to the argument passed in (which is undefined since you are not passing in anything) and not the items variable in your badgeCounter service which is the counter you are looking to return.

CodeWarrior
  • 2,721
  • 3
  • 18
  • 18