0

I have an array of items that I want to keep track of across several controllers. So, to do this, I made a service.

The service is basic for now, just adding items to an array and the ability to get the count:

angular.module('myapp.itemManagementService', [])
  .factory('myappItemSrv', [function () {
      var allItems = [];

      return {
          addItem: function (item) {
              allItems.push(item);
          },
          getItemCount: function () {
              return allItems.length;
          }
      };
  } ])
;

In my controller, I have a button that calls the addItem function and it is working fine, but I don't know how to bind the getItemCount so that the view auto-updates every time I add an item

In my controller, I have this:

$scope.count = myappItemSrv.getItemCount();

And then in the view

{{count}}

This only changes when I navigate away from the page, and then back

I realize that I am returning a value of a function and that won't bind, but I have no idea how to make this auto-update. I tried wrapping the call to addItem in a $scope.$apply call, but the error I get is:

Error: [$rootScope:inprog] $apply already in progress

1 Answer 1

1

getItemCount() is invoked once, when the controller is loaded. One way to do this is to put it on the scope...

$scope.getItemCount = myappItemSrv.getItemCount;

And change the binding...

{{ getItemCount() }}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.