Search code examples
javascriptangularjsangularjs-directiveangularjs-service

Angular service variable not updated in the view


I have the following service:

app.service('Cart', function() {
    this.data = [];
    this.addFont = function(font) { return this.data.push(font) };
    this.removeFont = function(i) { return this.data.splice(i, 1); };
    this.count = function() { return this.data.length; };
});

And the following directive, that displays a cart icon with the number of items in it:

app.directive('cartButton', ['Cart', function(Cart) {
    return {
        restrict: 'E',
        replace: true,
        template: '<button class="selection"><i class="fa fa-shopping-cart"></i> {{ Cart.count() }}</button>'
    };
}]);

But the counter doesn't work, and there is no error.

How to access Cart.count() inside my directive?


Solution

  • Angular expressions are evaluated against the scope.

    Try to set a function on the scope which will get the count from Cart:

    return {
        restrict: 'E',
        replace: true,
        template: '<button class="selection"><i class="fa fa-shopping-cart"></i> {{ getCartCount() }}</button>',
        link: function(scope) {
            scope.getCartCount = function() {
                return Cart.count();
            }
        }
    };