J.Olufsen
J.Olufsen

Reputation: 13915

How to return value from function that is passed from factory?

Currently in the view the totalCost is passed as a function to round, but it has to be integer value.

View

{{round(shoppingCart.totalCost)}}

Factory

myApp.factory( ....
var calculateTotalCost = function(){
    return this.items.map(function(item){
      return HelperFunctions.getPrice(item) * item.quantity;
    }).reduce(function(p, c){
      return p + c;
    });
  };
var factory = {
 shoppingCart: {order: currentOrder, totalCost: calculateTotalCost}
}
return factory;
}

How to solve it?

round : function (value) {
        return typeof value !== 'undefined'? value.toFixed(2): 0;
      }

Upvotes: 0

Views: 37

Answers (2)

Pankaj Parkar
Pankaj Parkar

Reputation: 136144

Currently you had totalCost variable which hold reference of calculateTotalCost function there in shoppingCart object. So while showing the same variable on view, you need to have service reference make available over the view by doing $scope.shoppingCart = shoppingCart

You could use number filter itself with precision 2 in your case, as you wanted to make the value fixed to precision 2. That will also help you to show the number in currency format.

{{shoppingCart.totalCost() | number:2 }}

Upvotes: 1

GG.
GG.

Reputation: 21844

You should avoid to call a function from a factory directly in a view expression.

In your directive's controller:

  1. Inject the factory.
  2. Call a function getTotalCost (which hides calculateTotalCost)
  3. Store the result in a variable.
  4. Apply the round function directly in the controller could be a nice idea too.
  5. Finally bind the variable to the view.

Upvotes: 0

Related Questions