Learn AngularJS – Basic Tutorial

This AngularJS tutorial is going to give you a very basic AngularJS knowledge. After this short but detailed AngularJS tutorial you will be able to quickly create powerful and intuitive web applications.

Let’s go – Getting started with AngularJS

Before we can do anything we need to create a simple HTML page that we can include AngularJS into. Create a file called “index.html” and use the following code:

<!DOCTYPE html>
<html>
<head>
     <title>Basic AngularJS Tutorial</title>
</head>
<body>
     <div id="content"></div>
</body>
</html>

We have a HTML page to work, now go to http://angularjs.org/ (opens a new tab) and copy the latest CDN link for AngularJS.

Or just use this one: https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js. Now you have the CDN location of the latest AngularJS version, include it within the head tags of your HTML page as follows:

<!DOCTYPE html>
<html>
<head>
     <title>Basic AngularJS Tutorial</title>
     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js" type="text/javascript"></script>
</head>
<body>
     <div id="content"></div>
</body>
</html>

Okkie, now we have Angular javascript included in our page. Let’s move to next step.

Setting Page for AngularJS App

In this step we are going to tell AngularJS that it needs to render this page as an application. It’s very simple to declare page as an AngularJS app. Simply add ng-app=”MyFirstApp” to the html tag as follows:

<!DOCTYPE html>
<html ng-app="MyFirstApp">
<head>
     <title>Basic AngularJS Tutorial</title>
     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js" type="text/javascript"></script>
</head>
<body>
     <div id="content"></div>
</body>
</html>

Now we have told that treat our index.html page as an AngularJS app. We can also add ng-app to DIV tag instead of HTML tag. I’m not going into detail as I want to keep this tutorial simple. Next we are going to declare which controller to use as follows:

<!DOCTYPE html>
<html ng-app="MyFirstApp">
<head>
     <title>Basic AngularJS Tutorial</title>
     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js" type="text/javascript"></script>
</head>
<body>
     <div id="content" ng-controller="MainController"></div>
</body>
</html>

MainController is the name of the controller and the #content DIV is controlled by it. But where is this controller? We need to make it! Within the same directory as you index.html file we need to create a JS file called app.js and it should look like the following:

var app = angular.module("MyFirstApp",[]);

The app.js file is creating an AngularJS app called MyFirstApp and assigning it to the app variable which we can use later on. Now we need to create another file called, maincontroller.js to define our mainController and it should look as follows:

app.controller("MainController", function($scope){
		
});

This is assigning a controller called, MainController to the MyFirstApp application. We can keep all this JavaScript within the same JavaScript file but it is good practice to separate them to keep your code maintainable and easier to understand. Just remember that app.js needs to be included before maincontroller.js. Lets do this now and include both files within HEAD tag.

<!DOCTYPE html>
<html ng-app="MyFirstApp">
<head>
    <title>Basic AngularJS Tutorial</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js" type="text/javascript"></script>
    <script src="app.js" type="text/javascript"></script>
    <script src="maincontroller.js" type="text/javascript"></script>
</head>
<body>
    <div id="content" ng-controller="MainController"></div>
</body>
</html>

Now let’s move to next step:

Understanding the Scope

In maincontroller.js code, you may have noticed the $scope variable that we added as a parameter to the controller function. This is where we will assign all our controller variables which will then make them available within the #content DIV in the HTML page. Take a look at the following example to understand this concept. Declare a $scope variable within the controller:

app.controller("MainController", function($scope){
    $scope.welcomemsg = "Welcome! Let's understand how the scope works!";
});

In above code, we simply create welcomemsg scope variable and assign a string to it. Now let’s look how we can access this scope variable in html page:

<!DOCTYPE html>
<html ng-app="MyFirstApp">
<head>
    <title>Basic AngularJS Tutorial</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js" type="text/javascript"></script>
	<script src="app.js" type="text/javascript"></script>
	<script src="maincontroller.js" type="text/javascript"></script>
</head>
<body>
    <div id="content" ng-controller="MainController">
		{{welcomemsg}}
    </div>
</body>
</html>

In above html code, you can find that I have wrap welcomemsg scope variable with {{}} so AngularJS knows it needs to do something with it. Now let’s check your index.html file in browser, you should see the following:

Capture01

Now you should understand what scope variables are and they are also available within the HTML by wrapping then with {{}}. Note that the scope is available only to that controller so you could not access the “welcomemsg” variable from outside the #content DIV, unless the same controller was defined.

So, it’s pretty cool that we can define a scope variable in JS and access it within HTML page. Now let’s move to next Data Binding concept. To understand this concept, declare a scope variable in MainController. Your whole maincontroller.js file will look as below:

app.controller("MainController", function($scope){
    $scope.inputValue = "";
});

Now edit index.html page as below:

<!DOCTYPE html>
<html ng-app="MyFirstApp">
<head>
    <title>Basic AngularJS Tutorial</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js" type="text/javascript"></script>
    <script src="app.js" type="text/javascript"></script>
    <script src="maincontroller.js" type="text/javascript"></script>
</head>
<body>
    <div id="content" ng-controller="MainController">
        <input type='text' ng-model='inputValue' />
        {{inputValue}}
    </div>
</body>
</html>

Above we have added a simple text input and used ng-model to bind it to the scope variable inputValue. Note how we did not wrap it in {{}} as it is being used within a ng-* tag. Additionally we are outputting the inputValue scope variable onto the page as we did before with the welcomemsg variable.

By doing all this we have bound the input value to the variable. This means that whenever the input value changes, the variable will update to match this. Open the page in a web browser and start typing within the input box. You should see something like the following:

Capture02

As you type the scope variable updates with the new input value and then as you are outputting the variable on this screen this also updates too, magic! This is how AngularJS two-way data binding.

Lets move on to a more complex example to get a better understanding of what is possible. Update maincontroller.js to look like below:

app.controller("MainController", function($scope){
    $scope.selectedStudent = 0;
    $scope.selectedGroup = null;
    $scope.student = [
        {
            id: 0,
            name: 'Ray',
            group: [
                'Music',
                'Dance',
                'Sports'
            ]
        },
        {
            id: 1,
            name: 'Chris',
            group: [
                'Sprots'
            ]
        },
        {
            id: 2,
            name: 'Harry',
            group: [
                'Music',
                'Dance'
            ]
        },
        {
            id: 3,
            name: 'Paul',
            group: [
                'Sports',
                'Music'
            ]
        }
    ];
});

We have declared three scope variables, selectedStudent is going to hold the object of the selected student. selectedGroup is going to hold the string value of the selected group. Finally we have an array of objects which are the student with array of group to which they belongs. What we are going to hope to achieve is have two select drop downs. One you will be able to select the student, then the other, thanks to binding will automatically update to allow you to select that student’s group. Lets add this HTML elements to our page:

<!DOCTYPE html>
<html ng-app="MyFirstApp">
<head>
    <title>Basic AngularJS Tutorial</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js" type="text/javascript"></script>
	<script src="app.js" type="text/javascript"></script>
	<script src="maincontroller.js" type="text/javascript"></script>
</head>
<body>
    <div id="content" ng-controller="MainController">
        <select ng-model='selectedStudent' ng-options='obj.name for obj in student'></select>
        <select ng-model='selectedGroup'>
            <option ng-repeat='label in student[selectedStudent.id].group'>{{label}}</option>
        </select>
    </div>
</body>
</html>

In html code, there are some new things so let’s go with each in detail. Firstly I have use select tag with ng-options directive. This allows us to populate this select input with the values from the student scope variable, using the name attribute within the student objects as the label, making the actual value of the select option, the object itself. You can read more about ng-options here. Play around and see what is possible.

Next select input is populated differently by using ng-repeat. It simply allows you to replicate HTML elements based on an array or set of objects. In the HTML above “ng-repeat” will create an option for each of the group within the student.group array based on the selectedStudent value which is determined by the first selected box as we have declared selectedStudent as its model as we did before with the input.

Within the ng-repeat option tag we have then put {{label}} between the opening and closing option tags, this is to output the label that we declared within the ng-repeat. Open it within the browser, select a student and you should see something like the following:

Capture03

So you can see that as we have used the model to bind the selects value we can then use this anywhere where the same scope is available to update other elements!

Note: student[selectedStudent.id].group is only working as the student ID#s are the same as the array indexes. This would not be an ideal solution in a real world situation as you cannot guarantee that the student ID#s will match the array index.

You should now have a good understanding of what binding is about and what is possible. We have also looked at ng-repeat and ng-options two powerful features of AngularJS.

Filter Data with AngularJS

Now let’s move to one more powerful feature of AngularJS. We are going to reuse student scope variable which we have created previously. Now our objective is to create interface which will allow us to search student by name and output the result to the page. Update index.html page to follow:

<!DOCTYPE html>
<html ng-app="MyFirstApp">
<head>
    <title>Basic AngularJS Tutorial</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js" type="text/javascript"></script>
    <script src="app.js" type="text/javascript"></script>
    <script src="maincontroller.js" type="text/javascript"></script>
</head>
<body>
    <div id="content" ng-controller="MainController">
        <input type='text' ng-model='searchText' />
        <ul>
            <li ng-repeat='s in student | filter:searchText'>#{{s.id}} - {{s.name}}</li>
        </ul>
    </div>
</body>
</html>

Here we added the input type text with a model searchText. And then we have create an un-ordered list of students by using ng-repeat which will iterate over the student array. Now open indext.html page in browser which will look as below:

Capture04

You will be able to see all the names of the student within the student array displayed within a list under the search input. Looking back at the HTML we can see some additional code within the ng-repeat. We have added a pipe | and then specified filter and then the model. This will call the AngularJS filter directive and provide it with the searchText model. The ng-repeat will then display results based on what the filter returns. Go ahead and type something within the text box and see the results automatically update. So this is how we can use filter in AngularJS.

Hope this quick AngularJS Tutorial gives you some basic idea to start developing AngularJS Application. You should now be able to go ahead and start creating your own AngularJS Application to learn more.

Advertisements

2 thoughts on “Learn AngularJS – Basic Tutorial

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s