1

I am new to javascript.

I am trying to understand how the value is set to 'USD' for 'outCurr' argument in the following code, am I missing anything. I understood the rest of the code but could not figure this out.

The example is taken from https://docs.angularjs.org/guide/concepts#model

angular.module('invoice1', []) 
    .controller('InvoiceController', function() 
    { 
        this.qty = 1; 
        this.cost = 2; 
        this.inCurr = 'EUR';
        this.currencies = ['USD', 'EUR', 'CNY']; 
        this.usdToForeignRates = { USD: 1, EUR: 0.74, CNY: 6.09 };

        this.total = function total(outCurr)
        {
            return this.convertCurrency(this.qty * this.cost, this.inCurr, outCurr);
        }; 

        this.convertCurrency = function convertCurrency(amount, inCurr, outCurr)
        {
            return amount * this.usdToForeignRates[outCurr] / this.usdToForeignRates[inCurr];
        };

        this.pay = function pay() {
            window.alert("Thanks!");
        }; 
    });

What I understand is that both function take 'outCurr' as argument/parameter but I cant see any value assigned to it. Please let me know if I have missed anything.

2 Answers 2

1

In the index.html file, there is an ng-repeat that loops through the current currencies (['USD', 'EUR', 'CNY'] array and calls total(c) function and pass each currency.

<b>Total:</b>
        <span ng-repeat="c in invoice.currencies">
          {{invoice.total(c) | currency:c}}
        </span>

So, you need to look at the html file too, as with AngularJS binding and expressions happens in the HTML file.

Hope that helps.

Sign up to request clarification or add additional context in comments.

1 Comment

No worries, if this answers your question please mark the question as answered for the benefit of other developers, Thanks.
0

The variable "outCurr" is assigned automatically once the function is called. In the code snippet you see here, the function convertCurr is never called in the Javascript. The special thing about AngularJS is that it enables these functions to be called in the HTML itself. You'll notice that, as explained by Omar, in the snippet below, it passes in the outCurr for each currency in the "currencies" array, thus displaying the resulting value in every currency.

<span ng-repeat="c in invoice.currencies">
    {{invoice.total(c) | currency:c}}
</span>

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.