With Angular.js I Created a Teaching Material in 15 minutes
Just as iron sharpens iron, friends sharpen the minds of each other. —Proverbs 27:17 (CEV)
When I do, I like to find new ways to help people see what actually happened. Anyway, this post isn’t about me; it’s about Angular.js. I used it to create an array visualizer to help visualize how sorting algorithms work, within 15 minutes.
Last Friday, I taught a younger friend about the sorting algorithms that she got from the Data Structures course: the Insertion Sort, the Selection Sort, and the Bubble Sort.
Now, showing how these algorithms work on paper would take a considerable about of time and writing. Also, I’m too lazy to write the same numbers over and over, so I told her, “wait while I code something up.”
Visualizing an Array
Then, I added some HTML code to display the array contents.
Within 5 minutes I have the array contents displayed.
I wanted to shuffle that array, so that we can sort. So I created a <button> and a $scope function to make it shuffle the array, and Angular.js takes care of the DOM for me.
Now, I wanted to be able to swap two elements in the array, so I can show her each of the sorting steps.
The design I had in my mind was to have a radio box to choose two item to swap, and then a “Swap” button to swap the selected elements.
And all of that can be done in 9 lines of code:
- Lines 11-12: the radio buttons that bind to the $parent’s scope variables a and b (remember we’re in “ng-repeat”).
- Line 17: A button that invokes the “swap” function on the $scope.
- Lines 20-24: A function to swap 2 elements in an array.
- Line 28: A function that is called when the Swap button is clicked. It swaps $scope.data using the indices from the $scope variables a and b (which is set when you click the radio button).
Showing It Step-By-Step
Actually, that was all that I needed: an array visualizer with the ability to shuffle the array and swap any two elements of the array.
So, I first showed her a shuffled array, and guided her through each step of the insertion sort algorithm. I swapped the array elements manually and explained along the way.
Finally, the Code
When she got the idea of how insertion sort worked, I wrote the actual insertion sort function into this array visualizer and added a <button> to call it.
Then, to show that it worked, I just click the “Shuffle” button, and then the “Insertion Sort” button, and the array became sorted.
Then in the same way I explained Selection Sort and Bubble Sort: First I showed her how the sorting algorithm works by manually swapping elements, then I wrote the code to bring the idea into reality.
Some time ago, before I know Angular, I wrote a Quicksort interactive demo. I had to do a lot of tedious DOM generation and manipulation myself, and the code became messy.
But with Angular, I don’t need to worry about that; I just focus on the logic. So I think Angular.js is very useful when you want visualize an idea or algorithm.