This is the second post of my learning experience with AngluarJS, Google’s HTML5/JS solution for building your own frameworks. In my first post I created an extremely simple app that added 2 values together. In this post I take that app a few steps further by creating a simple calculator.
This app demonstrates how to call scoped functions using button clicks, and how scoped variables can work together in an application.
Admittedly, the ‘simple’ calculator ended up being a little trickier than I thought at first. There are several ‘gotchas’ that tripped me up along the way. Some examples:
- There are special rules for the first number entered while the display output reads “0”. First, you don’t want to concatenate onto the 0. Second, if you enter a first number and then click the “add” button, no calculation should take place. This is especially important when subtracting where we would end up with -5 if “5 -” was entered. This is the reason the newNumber boolean variable is necessary.
- When the “equals” button is clicked the first time it should add all of the number that have been inputted together. The second and subsequent times it is clicked (before any new values are entered) it should repeat the last calculation. For example, if “8 + 2 =” is entered, 10 will be the answer. If the equals button is immediately clicked again, it should add 2 to the result and output 12. It should continue adding 2 until a new value is inputted. This is the main reason for the pendingOperation and lastOperation variables.
- The “add” and “subtract” buttons should only perform functionality when a value is pending. For example, “8 + 2 +++++++” should still result in a value of 10. This is unlike equals where the last action should be repeated (8 + 2 ===== equals 18).
- The add button should subtract, and vice versa, when a previous subtract operation is active. In other words entering “8 + 2 -” should result in 10 being displayed in the output as soon as the subtract button is clicked.
So, the simple calculator ended up being more of a challenge than I expected. That being said, I built the app to learn about AngularJS and demonstrate its functionality, not to reconcile my checking account.
If you want to learn a little more about AngularJS, try modifying the Fiddle to add the ability to multiply and/or divide.