Вопрос

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
Это было полезно?

Решение

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() }}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top