AngularJS Step-by-Step: Getting Started and Markup

- select the contributor at the end of the page -
This is the first in a series of blog posts intended to give you a taste of AngularJS without a lot of reading. If you decide you like what you see, check out the AngularJS Fundamentals Pluralsight course for a deeper introduction to Angular. Throughout this series I will link to fiddles on jsFiddle that you can use to follow along and will end with a complete fiddle. I recommend opening up the fiddle in a separate tab or window so you can easily follow along.

Getting Started

One thing that is helpful to remember, even though it may be self-evident since Angular is a JavaScript framework, is that everything that Angular does happens after the initial page load. So when an html page is downloaded, Angular parses the part of the page that you have identified as an Angular app.

To tell Angular what part of your page is an Angular app, you use the ng-app attribute. Often this attribute will be on an element that encompasses most, or all, of the body of the html page. It can be placed on any html container (such as html, body, div, etc). So somewhere you will have a tag that looks like this:

<html>

<body ng-app>

...

</body>

</html>

Here is a fiddle that has a reference to Angular and the html above to get us started (note that jsFiddle includes the html tag so you won't see it in the code).

Basic Markup

Just to prove that Angular will leave basic html alone, lets add a div with some content to the body. Update the above fiddle so that looks like the following and then run it:

  <body ng-app>

<div>Hello, World!</div>

</body>

Notice that you see the "Hello, World!" text as you would expect. Now let's add some simple Angular markup. Replace the div with the following and run the fiddle:

    <div>Hello {{1 + 1}} the World!</div>

There is your first Angular magic! You can see that the {{1 + 1}} expression got evaluated and replaced with "2". So, what happened here is that the page was downloaded and then Angular scanned the page for ng-app and processed any expressions that it found (in this case just the {{1 + 1}} expression) and replaced the content with the evaluated expression. If you would like to prove to yourself that the location of ng-app matters, try moving ng-app onto a div that does not include the {{1 + 1}} expression and you will see that the expression does not get evaluated (but any expressions inside the ng-app div do).

Model Binding

Angular is an MV* framework (specifically, it is MVC) and includes a robust yet simple-to-use model binding system. You can bind an input element to the model using the ng-model directive. A directive in angular is essentially a component that encapsulates content and/or functionality and most often is used as an html attribute, but you can actually create directives that are used as elements, classes, or even html comments. I will discuss directives more fully in a future post; for now, just know that there are a number of directives that come built in with Angular and ng-model is one of them.

You use ng-model to bind to the model like this:

    <input type="text" ng-model="firstName" />

You can also display values from a model anywhere in your html using an expression like this: {{user.firstName}}. Try adding the above input element to your fiddle and then update the Hello World div so that it says "Hello, _____" replacing the blank with the user's first name. Or you can just take a look at this fiddle which is already doing that.

Try typing in the text box and see what happens! Notice that Angular has created a 2-way binding between the model and the text box. How cool (and how easy) is that?!

Binding to an Array

What if you want to bind to an array and have html elements repeated for each item in the array? This is easy with ng-repeat. Before we demonstrate ng-repeat, however, we need to initialize some data on our model. Typically we'd do this in a controller, but I won't be talking about controllers until the next post so we're going to use the rarely used ng-init directive to add an array to our model. ng-init lets you execute angular expressions when the page first loads. Add this attribute to your <body> tag (if you moved your ng-app to another element be sure to move it back to the body tag or put the ng-init attribute on the element where your ng-app attribute exists, that will work fine too):

    ng-init="users = [{firstName: 'Jane', lastName: 'Doe', age:29}, {firstName: 'John', lastName: 'Doe', age: 32}]"

Now let's take a look at that ng-repeat directive. First add a div that looks like this:

    <div ng-repeat="user in users">

<div>

Now, put this content inside that div to make it interesting:

    {{user.firstName}} {{user.lastName}} - Age: {{user.age}}

Run your fiddle and see what you get! If you did things right you should see the info for each of the users displayed. Here is the fiddle. Pretty awesome, huh?

Advanced Tangent: Notice that we have a "user" on our model from the Hello World sample above, and yet inside the ng-repeat, the correct "user" object--from the users array--was used even though there was some ambiguous use of the term user. This is because the ng-model directive uses it's own isolated scope. Don't worry too much about this, just keep it in the back of your mind.

Filters

Filtering data with Angular is easy. Try updating the ng-repeat clause so that it now looks like this:

    <div ng-repeat="user in users | filter:'Jane'">

<div>

Now if you run the fiddle you can see that John Doe no longer shows up in the list. His data is still in the users array in the model, but the UI is filtering him out. You might ask, "How did this know to filter by first name?" Well, it didn't. That filter is actually looking for the existence of the 'Jane' anywhere in the data. Try changing the filter to 'Doe' and you'll see it will show both rows (since John and Jane have the same last name). Now try filtering for '32' or even '3'.

So what if you want to be more specific and filter just by a specific field. That's easy too, just pass in an object. Try changing that filter so that it looks like this

    <div ng-repeat="user in users | filter:{firstName: 'Jane'}">

Of course, filtering by 'Jane' would have worked with our previous filter, but change that filter so it filters by just the letter 'e' (i.e. {firstName: 'e'}). Notice that you only get Jane's record even though there is an 'e' in John Doe's last name; this illustrates that we really are filtering just by firstName. So, what if you want to be able to use that text box to filter by a specific field? Well, that text box is already bound to an object (not just a string) since it is bound to user.firstName. So try filtering by that user object (i.e. filter: user). Here is an updated fiddle.

Angular also comes with some built in filters for formatting data, which brings up another point: Filters aren't just for filtering and might be better named "transformations" or something similar. Think of filters basically as functions, I pass something in and I get something back. For example, there is a currency filter that you would use like this: "user.salary | currency" and that would format the data in a currency format. So while the "filter" filter limits the data based on criteria passed in to it, the "currency" filter formats data. You can also create your own filters. For example, I once created a filter that transforms an array into a comma separated list. You can learn more about built in and custom filters this in our AngularJS Fundamentals course.

Handling Events

So how about handling events with Angular? A lot of the basic mouse and keyboard events come with support for handling them via built-in directives in Angular. If you want support for other events, you can create a custom directive (a topic for a later blog post).

But for handling the most common events, it is as simple as adding an attribute to the element whose event you want to handle. To demonstrate this let's create a button that changes Jane's first name. Add a button at the bottom of the page that looks like this:

    <button ng-click="users[0].firstName = 'Jill'">Change Name</button>

Try clicking that button and you'll see that Jane's name immediately changes to "Jill". That's the basics of handling events using the built-in directives. Here is the final fiddle.

What about all this javascript in my html?

Of course, you wouldn't want to put all your JavaScript inside your html. It's already starting to look ugly with that ng-init at the top of the page and you can see how it would be a mess to put all your event handler code inside attributes. You really should do very little JavaScript inside your page. This is where controllers come in.

AngularJS is an MVC framework. So far you've seen us make use of the model (the users array is the model in the examples above and you can see how that model is available throughout the page), and you've seen us working in the view, but you have not yet seen controllers. Controllers will be the topic of the next post in this series and in that post you'll see how you can do things like call changeName('Jill') instead of inlining your JavaScript.

Can't wait for the blog post? Check out the course, now.

Next: AngularJS Step-by-Step: Controllers >

Ready to test your skills in AngularJS? See how they stack up with this assessment from Smarterer. Start this AngularJS test now.

 

Get our content first. In your inbox.

Loading form...

If this message remains, it may be due to cookies being disabled or to an ad blocker.

Contributor

Jim Cooper