Learn AngularJS in 30 minutes

 Learn AngularJS in 30 minutes

  • 2016-11-01
  • 2620

This AngularJS tutorial is going to take you through a streamlined set of instructions and cram pack you full of AngularJS knowledge within 30 minutes. After this short but detailed tutorial you will be able to quickly create powerful and intuitive web applications.

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>
    <head>
        <title>Learning AngularJS</title>
    </head>
<body>

</body>
</html>

Now that we have a HTML page to work with, head over 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>
<head>
    <title>Learning AngularJS</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>

Okay, now we have a HTML page and AngularJS included ready for use, lets move on.

SETTING UP THE PAGE FOR ANGULARJS

There are a few things we need to do to tell AngularJS that it needs to render this page as an application. As this is a quick AngularJStutorial we will not be going into detail as to how you can create multi-application and multi-controller pages, we are just going to declare this page as an AngularJS app, and its really simple!

Simply add ng-app=”MyTutorialApp” to the content DIV as follows:

<!DOCTYPE html>
<head>
    <title>Learning AngularJS</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-app='MyTutorialApp'></div>
</body>
</html>

Now we have told AngularJS that this DIV is an angular application, we need to declare which controller to use, as follows:

<!DOCTYPE html>
<head>
    <title>Learning AngularJS</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-app='MyTutorialApp' ng-controller='MainController'></div>
</body>
</html>

MainController is just a name that I made up, controllers should be named with some meaning and as this controller will be handling most of the application, main seems quite appropriate. Some would argue that this still is not enough definition, for this tutorial though, its fine! Okay, we now know what anything within the #content DIV will be controlled by the MainController, 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('MyTutorialApp',[]);

All this file is doing is creating an AngularJS app called MyTutorialApp and assigning it to the app variable which we can use later on. Now we need to create another file called, maincontroller.js and it should look as follows:

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

This is assigning a controller called, MainController to the MyTutorialApp application. All this JavaScript could be placed within the same JavaScript file but it is good practice to separate them out 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 out HTML so we can get started!

<!DOCTYPE html>
<head>
    <title>Learning AngularJS</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-app='MyTutorialApp' ng-controller='MainController'>
</div>
</body>
</html>

We now have the page and AngularJS application ready, lets move on with this AngularJStutorial.

UNDERSTANDING THE SCOPE

When we created the 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.understand = "I now understand how the scope works!";
});

In the above code we simply created a scope variable and assigned a string to it. Now we can access this within our HTML.

<!DOCTYPE html>
<head>
  <title>Learning AngularJS</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-app='MyTutorialApp' ng-controller='MainController'>{{understand}}</div>
</body>
</html>

Within the above HTML we wrap the understand variable with {{}} so AngularJS knows it needs to do something with it. Note how we have not added the $scope. to the front of the variable name. If you now view your index.html file within a browser, you should see the following:

enter image description here

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

UNDERSTANDING BINDING

So, it was pretty cool that we can declare a scope variable within the JS and instantly access it within the HTML, but AngularJS can offer so much more.

Data binding is a large topic but this AngularJS tutorial will cover the most important parts to ensure you understand what is possible and allow you to investigate further on your own. To understand this concept, lets declare a scope variable which will act as a model. Modify maincontroller.js to look as below:

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

Now lets add some additional HTML to our page:

<!DOCTYPE html>
<head>
  <title>Learning AngularJS</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-app='MyTutorialApp' 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 understand 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:

enter image description here

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!

Now you have a way of keeping various elements and values in sync within the page. 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.selectedPerson = 0;
  $scope.selectedGenre = null;
  $scope.people = [
    { id: 0, name: 'Leon', music: [ 'Rock', 'Metal', 'Dubstep', 'Electro' ] },
    { id: 1, name: 'Chris', music: [ 'Indie', 'Drumstep', 'Dubstep', 'Electro' ] },
    { id: 2, name: 'Harry', music: [ 'Rock', 'Metal', 'Thrash Metal', 'Heavy Metal' ] },
    { id: 3, name: 'Allyce', music: [ 'Pop', 'RnB', 'Hip Hop' ] }
  ];
});

We have declared three scope variables, selectedPerson is going to hold the object of the selected person. selectedGenre is going to hold the string value of the selected genre. Finally we have an array of objects which are people with their own musics tastes. What we are going to hope to achieve is have two select drop downs. One you will be able to select the person, then the other, thanks to binding will automatically update to allow you to select that persons music genres. Lets add this HTML elements to our page:

<!DOCTYPE html>
<head>
  <title>Learning AngularJS</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-app='MyTutorialApp' ng-controller='MainController'>
    <select ng-model='selectedPerson' ng-options='obj.name for obj in people'></select>
    <select ng-model='selectedGenre'>
      <option ng-repeat='label in people[selectedPerson.id].music'>{{label}}</option>
    </select>
  </div>
</body>
</html>

There are some new bits here so lets look at them in detail. Firstly we have a select input with ng-options tag. This allows us to populate this select input with the values from the people scope variable, using the name attribute within the person objects as the label, making the actual value of the select option, the object itself. This AngularJS tutorial is not going to go into great detail of ng-options you can read more about that here. Play around and see what is possible.

The next select input is populated a different way, for demonstrative purposes. The ng-repeat directive in my mind is one of the most powerful features of AngularJS. ng-repeat 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 music genres within the people.music array based on the selectedPersons ID value which is determined by the first selected box as we have declared selectedPerson as its model as we did before with the input.

Within the repeated 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 person and you should see something like the following:

enter image description here

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

**Note:**people[selectedPerson.id].music is only working as the people 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 people 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.

FILTERING DATA WITH ANGULARJS

This AngularJS tutorial is now going to cover filtering as this is another super powerful AngularJS feature. We are going to reuse the people scope array from the previous section and create a simple interface that will allow us to search for the people’s names and output the results to a page. Update your HTML as follows:

<!DOCTYPE html>
<head>
  <title>Learning AngularJS</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-app='MyTutorialApp' ng-controller='MainController'>
    <input type='text' ng-model='searchText' />
    <ul>
      <li ng-repeat='person in people | filter:searchText'>#{{person.id}} {{person.name}}</li>
    </ul>
  </div>
</body>
</html>

Here we have added a text input and provided it with a model searchText we don’t need to declare this physically in the scope within maincontroller.js. We have also created a un-ordered list and added an ng-repeat to the list element which will create a list element for every person within the people array which we created in the last section. If you open this in your browser now, you should see the following:

enter image description here

You will be able to see all the names of the people within the people 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.

Filtering is as simple as that! This AngularJS tutorial will not cover more advance filtering or custom filters, but keep tuned for more AngularJS tutorials that will!

HIDING AND SHOWING ELEMENTS WITH ANGULARJS

This section of the AngularJS tutorial is going to look at how you can hide and show elements. We are going to continue using the people array as our data-set but we need to add some additional data to allow us to demonstrate ng-show and ng-hide. Update your maincontroller.js file as follows:

app.controller("MainController", function($scope){
  $scope.people = [
    { id: 0, name: 'Leon', music: [ 'Rock', 'Metal', 'Dubstep', 'Electro' ], live: true },
    { id: 1, name: 'Chris', music: [ 'Indie', 'Drumstep', 'Dubstep', 'Electro' ], live: true },
    { id: 2, name: 'Harry', music: [ 'Rock', 'Metal', 'Thrash Metal', 'Heavy Metal' ], live: false },
    { id: 3, name: 'Allyce', music: [ 'Pop', 'RnB', 'Hip Hop' ], live: true }
  ];
});

You can see that we have added a live flag to each of the people, the only person with the flag set to false is Harry. To demonstrate both ng-hide and ng-show, add an additional un-ordered list to your HTML as follows:

<!DOCTYPE html>
<head>
  <title>Learning AngularJS</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-app='MyTutorialApp' ng-controller='MainController'>
    <input type='text' ng-model='searchText' />
    <ul>
      <li ng-repeat='person in people | filter:searchText'>#{{person.id}} {{person.name}}</li>
    </ul>
    <ul>
      <li ng-repeat='person in people | filter:searchText'>#{{person.id}} {{person.name}}</li>
    </ul>
  </div>
</body>
</html>

This will simply output the same data twice. Now we are going to use ng-hide and ng-show to conditionally hide list elements based on the live flag we have just created. Update your HTML to match the below code:

<!DOCTYPE html>
<head>
  <title>Learning AngularJS</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-app='MyTutorialApp' ng-controller='MainController'>
    <input type='text' ng-model='searchText' />
    <ul>
      <li ng-repeat='person in people | filter:searchText' ng-show='person.live == true'>#{{person.id}} {{person.name}}</li>
    </ul>
    <ul>
      <li ng-repeat='person in people | filter:searchText' ng-hide='person.live == false'>#{{person.id}} {{person.name}}</li>
    </ul>
  </div>
</body>
</html>

As you can see ng-show and ng-hide are used in exactly the same way, except they are the opposite of each other (obviously). In the above example we are referencing the person variable which is declared as part of the ng-repeat and just evaluation whether its live attribute is true or false. If you open this example in your browser you will see that Harry no longer appears in either list.

enter image description here

And that is how easy it is to conditionally hide or show an element with AngularJS.

EVENTS WITH ANGULARJS

The final part of this quick AngularJS tutorial will look at events. Events have always been a powerful feature of JavaScript frameworks such as jQuery and this has not changed with AngularJS. To demonstrate this we are going to add another input and a button to our HTML as below:

<!DOCTYPE html>
<head>
  <title>Learning AngularJS</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-app='MyTutorialApp' ng-controller='MainController'>
    <input type='text' ng-model='searchText' />
    <ul>
      <li ng-repeat='person in people | filter:searchText' ng-show='person.live == true'>#{{person.id}} {{person.name}}</li>
    </ul>
    <input type='text' ng-model='newPerson' />
    <button ng-click='addNew()'>Add</button>
  </div>
</body>
</html>

We have just added an input with a model newPerson and a button with ng-click which will call a function called addNew. We now need to update our maincontroller.js file as follows:

app.controller("MainController", function($scope){
  $scope.people = [
    { id: 0, name: 'Leon', music: [ 'Rock', 'Metal', 'Dubstep', 'Electro' ], live: true },
    { id: 1, name: 'Chris', music: [ 'Indie', 'Drumstep', 'Dubstep', 'Electro' ], live: true },
    { id: 2, name: 'Harry', music: [ 'Rock', 'Metal', 'Thrash Metal', 'Heavy Metal' ], live: false },
    { id: 3, name: 'Allyce', music: [ 'Pop', 'RnB', 'Hip Hop' ], live: true } ];
  $scope.newPerson = null;
  $scope.addNew = function() {
    if ($scope.newPerson != null && $scope.newPerson != "") {
      $scope.people.push({ id: $scope.people.length, name: $scope.newPerson, live: true, music: [] });
    }
  }
});

The above JS shows that we have declared the newPerson scope variable and a scope function addNew which will be called on the button click thanks to the ng-click we added to the button.

Within the addNew function we are just checking that the newPerson value is not null or empty and then added a new object to the end of the people array. This is a very simple example of how a click event can be used within AngularJS. There are many more available such as ng-change, ng-checked, ng-select, etc but this AngularJS tutorial will not go into any more detail, you can head over to AngularJS if you want to learn more.

CONCLUSION

This quick AngularJS tutorial should have given you enough to understand how AngularJS works on a high level and what it is capable of. You should now be able to go ahead and starting creating your own AngularJS applications to learn more.

View the demo or look at the code.

Suggest

Angular 2 Fundamentals: Learn By Creating A Real Web App

Angular 2 Concepts, Code and Collective Wisdom

Understanding TypeScript

Quickstart AngularJS

JavaScript Promises: Applications in ES6 and AngularJS

Filters in AngularJS