Introduction to AngularJS – Part 1

AngularJS has been in the javascript universe for more than three years and has been booming in the last year through community activities and regular bug fixing.
Thanks and congratulations to everyone out there who helped build this life saving tool.

AngularJS helps you create single page web applications very swiftly. Lets create a basic web application super quickly in which we will be performing CRUD operations on a Student resource (this will not be a client-server application; just plain sober AngularJS and HTML). Lets fasten our seat belts and fly the angular way.

First things first. Lets create an AngularJS app:

var myApp = angular.module('student', []);

Now that we have created an application. Let us bind this application with our html.

<html ng-app="student">
    <head>
        <script type="text/javascript" src="js/angular.min.js"></script>
        <script type="text/javascript" src="js/app.js"></script>
        <link href="css/bootstrap.min.css" rel="stylesheet" type="text/css">
    </head>
    <body>
        <div class="container">
            <h1>Students</h1>
        </div>
    </body>
</html>

In the above HTML you can see I have used ng-app="student", this is how to bind your angular app to HTML. You can place this attribute anywhere in your template, and your app will run within that scope. The ng-app attribute basically represents a directive provided by AngularJS, ngApp. You can create your own directive by following the convention name-with-dashes for attribute names and camelCase for the corresponding directive name. We need a controller Student that will perform all the required actions, so lets create one.

function StudentController($scope){
    $scope.students = [
        {name: "Nikhil Jain", age: 27},
        {name: "Rohit Sharma", age: 23},
        {name: "Suvish T", age: 22}
    ];
}

And modify our template with the code below:

<body ng-controller="StudentController">

In the above code, we have merely declared a javascript function, StudentController. But on the view side, we have binded this function to the template using the directive ng-controller. When the binding is in process, data in the function is attached to the $scope parameter which was passed. Now whatever data the $scope variable carries will be available to the app on the view side.

The concept of a scope in Angular is crucial; a scope can be seen as the glue which allows the template, model and controller to work together. Angular uses scope, along with the information contained in the template, data model, and controller, to keep models and views separate, although in sync. Any changes made to the model are reflected in the view; any changes that occur in the view are reflected in the model.

Now that the controller is binded to the template. Let us iterate the students array attached to the scope, and render the data.

<table class="table">
    <tr>
        <th>Sr. No.</th>
        <th>Name</th>
        <th>Age</th>
    </tr>
    <tr ng-repeat="student in students">
        <td>{{$index + 1}}</td>
        <td>{{student.name}}</td>
        <td>{{student.age}}</td>
    </tr>
</table>

See how easy it is to create apps the Angular way? Everything falls into place without lifting a finger. In the above template the
tag has an attribute ng-repeat; this is another directive, ngRepeat, provided by AngularJS for iterating javascript objects on dom and rendering them accordingly. Now let us try to create an new student object. Lets prepare by defining a function inside the controller:

$scope.newStudent = function(){
    $scope.enterNew = true;
    $scope.student = {};
};

And modify the template to encompass this as well:

<div class="container row">
    <h1 class="pull-left">Students</h1>
    <a class="btn btn-info pull-right" ng-click="newStudent()">New Student</a>
    <br/>
    <div class="row">
        <table class="table">
            <tr>
                <th>Sr. No.</th>
                <th>Name</th>
                <th>Age</th>
            </tr>
            <tr ng-repeat="student in students">
                <td>{{$index + 1}}</td>
                <td>{{student.name}}</td>
                <td>{{student.age}}</td>
            </tr>
        </table>
    </div>
    <div ng-show="enterNew">
        <form>
            <div class="row">
                <div class="span1">Name</div>
                <div class="span4">
                    <input type="text" class="input" ng-model="student.name" />
                </div>
            </div>
            <div class="row">
                <div class="span1">Age</div>
                <div class="span4">
                    <input type="text" ng-model="student.age" />
                </div>
            </div>
            <div class="row">
                <div class="span5">
                    <input type="submit" class="btn btn-primary" value="Save" ng-click="saveStudent()"/>
                </div>
            </div>
        </form>
    </div>
</div>

Study the form carefully. We have not used the name attribute for any input field. Instead we have an attribute ng-model for each input field. This is another directive provided by AngularJS for two-way data binding (controller to view and vice-versa). We have also used the directives ng-click for the Submit button. This directive has binded the onclick event to the Submit button, which if encountered will call the function in the attribute value. ng-show is used to toggle the display status of any element on the dom. When ng-show receives a true value it displays that block, otherwise it hides the block. The inverse to this is ng-hide, which helps you go the other way around.

We can now add saveStudent() to our controller.

$scope.saveStudent = function(){
    $scope.students.push($scope.student);
    $scope.enterNew = false;
};

With the above table, we can watch values get added to the students table automatically. We’ve completed the create and read portions; now lets update the pre-added values.

To the students table add another table header Actions, and under that provide an edit link for all the entries, as shown below:

<table class="table">
    <tr>
        <th>Sr. No.</th>
        <th>Name</th>
        <th>Age</th>
        <th>Actions</th>
    </tr>
    <tr ng-repeat="student in students">
        <td>{{$index + 1}}</td>
        <td>{{student.name}}</td>
        <td>{{student.age}}</td>
        <td><a ng-click="editStudent(student)">Edit</a></td>
    </tr>
</table>

Now add another form (to easily differentiate between the create/update functionality) as below:

<div ng-show="editing">
    <form>
        <div class="row">
            <div class="span1">Name</div>
            <div class="span4">
                <input type="text" class="input" ng-model="student.name" />
            </div>
        </div>
        <div class="row">
            <div class="span1">Age</div>
            <div class="span4">
                <input type="text" ng-model="student.age" />
            </div>
        </div>
        <div class="row">
            <div class="span5">
                <input type="submit" class="btn btn-primary" value="Save" ng-click="updateStudent()"/>
                <a class="btn" ng-click="cancelSave()">Cancel</a>
            </div>
        </div>
    </form>
</div>

The template is ready to handle the update feature, but since none of the functions used have been declared, won’t it give an error? The answer is no. If a dom element tries to call any function through a directive, AngularJS checks whether that function is defined, if it’s defined AngularJS calls it properly, but if it isn’t defined it does not throw an error. Now we can make the additions for updateStudent feature in our controller.

$scope.editStudent = function(student){
    $scope.enterNew = false;
    $scope.editing = true;
    $scope.student = student;
};
$scope.updateStudent = function(){
    $scope.enterNew = false;
    $scope.editing = false;
};

It’s now time to create the delete function. First we’ll have to add a Delete link in the Actions column of the Student table.

<a ng-click="deleteStudent(student)">Delete</a>

Now we will have to define the deleteStudent() function inside the controller.

$scope.deleteStudent = function(student){
    var index = $scope.students.indexOf(student);
    $scope.students.splice(index,1);
}

And thats all there’s to it! A basic standalone Angular Application, that demonstrates how to perform complex tasks with ease.

All this code (and future updates) can be found on GitHub.

Stay tuned for the next post, which will be about using AngularJS against a REST API.

3 thoughts on “Introduction to AngularJS – Part 1

  1. shyam on said:

    Hi Rohit.. Thanks a lot. This really helped me to get started with AngularJs

  2. Matt on said:

    I sure appreciate this tutorial and can’t wait to get to the next part on creating an API.

    I did notice a little problem with this version that I think comes from a functionality that will only be available once we’re retrieving and updating data. When you edit a student, the changes are reflected immediately in the table and the “Cancel” button does nothing (obviously we don’t have a cancelSave() function in our controller).

    As I said, I’m sure this will work perfectly once we starting really updating data through an API.

    Thanks again for this great starter tutorial!

  3. ritz on said:

    hi Rohit do u know how to take student name and display it in text area on
    button click

Leave a Reply

*

*