Today I learned… in code

A lot happens between "Hello World" and "Supreme Master Programmer". Here, we share little discoveries made along the way. The more frustrating something was, the more likely it is to end up here on this site!

The rest of this post is about the app itself (not its code). If you’re hoping for some code walkthroughs, stay tuned – I’ll be writing a few in the next month or two before I move onto my next side project.

App inspiration

I started OSU’s online CS degree program Fall 2016, and I am so grateful for the opportunity the school has given me to receive a formal CS education.

Ever since I applied to the program I’ve been an avid reader of the OSU CS subreddit. I was always looking for info on my next class – survival tips, strategies, what to study, etc. The course survey (linked in the sidebar) contains years of useful student data but at 300+ entries, it was becoming difficult to browse or parse on a macro level (ie: there was no way to look at it and determine how time-consuming on average a particular class might be).

I had the idea for a simple web app that would take the Google spreadsheet data and reorganize it by course, listing all the tips (with timestamps) and aggregating the time spent and difficulty data into a couple of easy-to-read pie charts. I knew other people would find this useful, too, so I planned to make it publicly and freely available once it was presentable. (From this experience I also wanted a finished, portfolio-worthy app that I might show to a potential employer.)

I started the project in the summer of 2017, worked on it bit by bit whenever I wasn’t swamped with classwork (or my full-time job, or my baby who was 9-13 months old while I worked on this, or the cross-country move I did in August). It’s definitely a testament of what you can build even if you don’t have loads of contiguous free time, as long as you are consistent and keep going.

Browse the code

If you want to browse the app’s progress (and see some of the mistakes I made along the way) you can browse the GitHub repo for it here. I tried to leave concise comments explaining what I was doing, in hopes that other students and beginning web devs would find it helpful.

I plan to write a few blog posts dedicated to different sections of the app’s code. I love “here’s an app I built and how I built it” type posts myself and owe a lot of my own knowledge to them, so I’ll try to give back a few contributions of my own.

Why I chose AngularJS

I know everyone’s got the hots for React these days but I had just come off of 2 years of working in Ember and wanted to return to my ancestral headwaters for a bit and build something in the framework I got my start in. I wanted to see if all my “I liked how that worked in Angular better” feelings towards Ember were actually accurate or just some rose-colored tinting of history (as it turns out, I really do prefer Angular to Ember :P)

I don’t know if I’d pick it again, though. The world has largely moved on from AngularJS (to Angular 2 and beyond, and React), but there’s still a ton of helpful blog posts and Stack Overflow questions about every imaginable Angular topic (way more than Ember has, that’s for sure) so for that reason, I think it’s still a good, established choice if you’re new to web development frameworks and want to try something.

Thanks to contributors

Special thanks goes to Yong Joseph Bakos for his pull requests after the project launched – cleaning up some cruft in the codebase, improving tests, documentation, etc.

Special thanks also goes to Jonathan Burley for helping unstick me at some critical points in development, like when I needed help customizing the canvas legends in a way that wasn’t documented and when Heroku was being a pain.

I feel like I always learn so much from even the briefest encounters with other developers, so I am grateful for the help I received along the way.

This comes with a noticeable caveat: it complicates your template code. Generally, it’s considered good practice to minimize the amount of logic that happens in an html template. If you need to do many things on a single ng-click, you should consider writing (or refactoring) a method in your controller to handle them with just one method call.

Nonetheless, this odd bit of Angular syntax can be useful, even if it never makes it to production. In my case, I needed to modify $parent.someVar on click, which was (at the time) outside of the button’s controller. Ultimately, this code was refactored so that someVar could be modified from within selectTab(), but when I needed a quick and dirty implementation to demo something, chaining functions on a single ng-click got the job done.

Wait, what does $parent.someVar do? What is $parent?

$parent allows code within a child controller to access something contained within the parent scope.

Today I learned… there are [at least] two ways to inject a service into Mocha unit tests using the Chai assertion library and Angular mocks. This is just a little thing, but I’ve seen this difference in a few unit testing tutorials and it confused me the first time I came across it.

In my project I have a service called mealsServer. No need to worry about what it does, for now we’re just testing that it gets injected successfully (in other words, exists).

Service Injection Technique #1:

Here I am declaring mealsServer as a variable and then injecting _mealsServer_ using beforeEach:

The underscores are an oddity. The underscores are a little syntax trick that make it possible to use the same name for the injection as we use for the variable. In other words, if we didn’t inject _mealsServer_ wrapped in underscores, then var mealsServer would need a different name. I’m all for keeping names consistent whenever possible, so I’m glad I learned about this.

Service Injection Technique #2:

And here’s an alternative: here I am injecting the mealsServer service as part of the it block:

it('should have a working meals-server service', inject(function(mealsServer) {
expect(mealsServer).to.exist;
}));

I’m still learning the ropes of unit testing, so I’m sure there are advantages/disadvantages to each of these approaches. I’m relying a lot on this tutorial: Testing AngularJS Apps Using Karma to get me started.

Personally, I like injecting the service in the same line of code that relies upon it being there. I think this is neater and will hold up better as this file becomes longer.

For reference’s sake, here’s the complete meals-test.js file below. It’s small right now, but just getting to the point of having (any!) tests run successfully was a several hour endeavor. In this version, I am just testing that my services exist and I’m using technique #2 from above.

This tutorial is about a neat trick you can use with ng-repeat and inputs using AngularJS. This is just one tiny part of a larger AngularJS project of mine you can explore here: Chicken Breast Meals on GitHub.

Let’s say you are building a user input form that lets the user input series of items in a list, such as ingredients in a recipe. You could have the user click a link to add a new input field before typing in each ingredient, but that’s an extra (and annoying) step nowadays for users.

What you really want is a list of inputs that grows itself, offering a new blank input in response to each addition the user makes:

When the user selects a recipe to edit in the admin page, that selected recipe is represented by an object called formMeal. Inside formMeal are properties like:

name (which is saved as a String)

yield (saved as a Number)

cookTime (another Number)

ingredients (an Array of Objects)

On the <li>

The ng-repeat directive builds the list of ingredients by creating a <li> and a <textarea> for each ingredient already found in the saved recipe data. Each ingredient has an index in the ingredients array, so we grab its name out of the array of ingredient objects like so:

formMeal.ingredients[$index].name

Immediately following the ng-repeat directive is $track by index. This bit of code is easy to overlook but it’s very important: it’s what keeps the user’s current textarea in focus while the user edits it. Without $track by index, the app kicks the user out of that text box after the first typed letter. (Ask me how much fun I had debugging this lose-focus problem…)

In the <textarea>

Each ingredient is represented by a <textarea>, and each one has its own ng-model directive pairing it with that particular index in the array.

This is what puts the default text into each <textarea> when the user hasn’t entered anything yet. It’s just a nice UX touch.

Finally, we have an ng-change directive. You can read more about ng-change here, basically all it does is call the method (or do the thing) you tell it to do any time there’s a change in the <textarea> it’s associated with.

data-ng-change="changeIngredient($index)"

A change to the <textarea> (ie: user typing) causes the method changeIngredient() to run with each change.

Part 2: In the controller (.js file)

We already saw that whenever the user updates text inside one of those <textarea> regions, this method gets called. (If you were to put a console log inside changeIngredient(), you would see it called every time you typed a letter into the textarea.)

if that index is at the end of the array (ie: its index number is one less than the array’s length), then we are editing the last ingredient in the list and we need to push an empty ingredient (”) to the ingredients array to make the empty box appear at the end

if that index is not at the end of the array, we just update whatever’s at this index since it’s an ingredient that already exists. This is why you don’t see an empty box get added to the end of the list if you’re editing a field that’s not at the end.

It’s important to observe that this method works by checking that the user is editing the last index (which is always the empty <textarea>). This is how we don’t spawn new, empty textareas for editing earlier ingredients in the list.

Part 3: Offering an empty field by default

When you initialize your data or your app, you’ll need to include something like:

$scope.formMeal.ingredients = [''];

or

$scope.ingredients.push('');

so that the ingredients list has an empty one in it by default. Your implementation needs will vary, of course, but hopefully this little guide gave you enough of a start to build this “infinity list” into your own AngularJS form!

Don’t miss the Plunker demo of a simplified version of this feature that you can play with and adapt to your own project.