Question

I have a factory defined like this:

mob.factory("OrderHelper", function() {
    return {
      lineItemPrice: function(lineItem) {
        return lineItem.price * lineItem.quantity;
      },
      orderTotal: function(order) {
        order.items.forEach(function (item)) {
          total += lineItemPrice(item);
        }
      }
    }
});

That problem is that I can't use the method "lineItemPrice" in "orderTotal" method. It throws this error: Error: [$interpolate:interr] Can't interpolate: £{{orderTotal(order)}} Can somebody please tell how can I call a method from a function in the same factory.

Thanks.

Was it helpful?

Solution

you could also do it like this:

mob.factory("OrderHelper", function() {
    var methods = {};

    methods.lineItemPrice = function(lineItem) {
      return lineItem.price * lineItem.quantity;
    };

    methods.orderTotal = function(order) {
      order.items.forEach(function (item)) {
        total += methods.lineItemPrice(item);
      }
    };

    return methods;
});

OTHER TIPS

Try this (the revealing module pattern):

mob.factory("OrderHelper", function() {
    var lineItemPrice = function(lineItem) {
      return lineItem.price * lineItem.quantity;
    };

    var orderTotal = function(order) {
      order.items.forEach(function (item)) {
        total += lineItemPrice(item);
      }
    };

    return {
      lineItemPrice: lineItemPrice,
      orderTotal: orderTotal
    }
});

You can use angular.foreach() to iterate each items and supply the third parameter as the context of the callback function.

mob.factory("OrderHelper", function() {
    return {
      lineItemPrice: function(lineItem) {
        return lineItem.price * lineItem.quantity;
      },
      orderTotal: function(order) {
        var total = 0;

        angular.forEach(order.items, function(item) {
          total += this.lineItemPrice(item)
        }, this); // add `this` as the context of the callback

        return total;
      }
    }
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top