A Little Bit of Angular in My Life

My team, Copypasta, and I recently had a project in angular and we spent a good portion of that time being kind of confused about how it all works. Let me break it down.

When using angular, the first and most important thing, is making sure you have angular. I prefer to use a CDN but you can also download it using npm. The CDN can be found here. If you use the cdn you’ll need to put a script tag in your html in the head. That will look like this: <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.js"></script>

Note: Do not use a cdn with ‘min’ in the path while developing. It will not return descriptive or useful error messages.

After adding angular to your app, you need to use it. At the top of a ‘js’ file, insert the following line of code:

angular.module('ANY_NAME_YOU_CHOOSE', [])

This will initialize your app with what ever name you have chosen. ‘app’ is a popular choice. Whatever name you choose will have to be consistent across all files you plan to use angular in. You’ll need to add a similar line of code to the top of any other ‘js’ file you plan to use angular inside of. The key difference will be the absence of [] . This will reinitialize your app, so don’t do that. angular.module('THE_NAME_YOU_CHOSE') . There are some minor differences you might see in this syntax as you google.

For instance, I did not use a semi-colon to end these lines because I prefer to chain directives and controllers, rather than add them as properties on a variable. That would look something like this:

const app = angular.module('app', []);

Then to add a controller you would add:

app.controller('appCtrl', function () {function body});

However if you don’t add the semi colon you can chain controllers and directives, etc, just by using .controller('appCtrl', function(){function body}) . In this case you wouldn’t use the semi-colon until you had completed adding things to this instance of the angular module.

Let me back up and explain what needs to happen in your html after you have initialized your app in your ‘js’ file. In either the body tag or the head tag you must insert the command ng-app="YOUR_APP_NAME" . This essentially defines the entry point of angular into your app. This line of code says that instances with the same name (remember I said that was important) can be used. You will also need to include a script tag for every file you need to use, placed just before the closing body tag. Remember load order matters. Your entry point tag should go first. You may have to play with this, but remember, if a file relies on another file to work, it should go somewhere underneath that file when added to the html.

That’s it for now. Come back next time for controllers and directives.


Like what you read? Give Daniel Weill a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.