Friday, 17 March 2017

PRODUCT FORM USING PHP AJAX AND BOOTSTRAP

Database:

database name:product_database

tablename:product

field:
p_id
p_name
p_code

tablename:category

field:
c_id
c_name

tablename:product_category

field:
id(primary key)
product_id(forign key) with p_id
category_id(forign key) with c_id


index.php 


<!DOCTYPE html>
<html lang="en">
<head>
<title>PRODUCT</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="js/bootstrap.min.css">
<script src="js/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script type="text/javascript" src="js/transaction.js"></script>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>

<div class="container">
<h2 class="text-center">PRODUCT</h2>
<form id="product" method="POST">
    <div class="form-group">
      <label for="name">Name:</label>
      <input id="name" type="text" name="name" class="form-control">
 <span id="error"></span>
    </div>
    <div class="form-group">
      <label for="code">code</label>
      <input id="code" type="number" name="code" class="form-control">
 <span id="error"></span>
    </div>

<div class="form-group">
<label for="category">Category</label>
<?php
include "conn.php";
$res = mysqli_query($con,"SELECT * FROM category");
while($row = mysqli_fetch_assoc($res))
{
?>
&nbsp;&nbsp;&nbsp;&nbsp;
<span><?php echo $row['c_name'] ?></span>
<input type="checkbox" id="<?php echo $row['c_id'];?>" name="cat[]" class="checkbox-inline" value=<?php echo $row['c_id']; ?> />
<?php
}
?>
</div>

<div class="form-group">
            <button id="add" name="add" type="button" class="btn btn-primary btn-md">ADD</button>
            <button id="resetform" name="reset" type="reset" value="Reset" class="btn btn-primary btn-md">Reset</button>
</div>

<div class="form-group">
<table id="display" class="table table-striped table-responsive">
<thead>
<tr>
<th>Update</th>
<th>Delete</th>
<th>Name</th>
<th>Code</th>
<th>Category</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</form>
</div>
</body>
</html>


conn.php


<?php  
$con=mysqli_connect("localhost","root","","product_database");
?>


view.php


<?php
include "conn.php";
?>
<?php 
$json = array(); 
$query = mysqli_query ($con, "SELECT P.p_id AS 'product_id', P.p_name AS 'product_name',P.p_code AS 'product_code', GROUP_CONCAT(C.c_name) AS 'category_name' FROM Product P LEFT JOIN product_category PC ON P.p_id = PC.product_id LEFT JOIN category C ON PC.category_id = C.c_id GROUP BY pc.product_id");
while($row = mysqli_fetch_assoc($query))     
{
$bus = array(
'p_id' => $row['product_id'],
'p_name' => $row['product_name'],
'p_code' => $row['product_code'],
'c_name' => $row['category_name'],
                        'result' => 'success'
);
array_push($json, $bus);
}
        $jsonstring = json_encode($json);
        echo $jsonstring;
?>


insert.php


<?php

include "conn.php";
?>
<?php

//name is set then execute belove code 
if (!empty($_POST['name'])) {
    $p_name = $_POST['name'];
    $p_code = $_POST['code'];
   
    //insert data in product table(name,code)
    mysqli_query($con, "insert into product values('','$p_name','$p_code')");

    //get last insert id from product table
    $p_id = mysqli_insert_id($con);

    //category is selected then execute belove code
    if (!empty($_POST['cat'])) {
        $category = $_POST['cat'];
        $c_name = array();

        //insert selected category in product_category table
        foreach ($category as $cid => $c_id) {
            mysqli_query($con, "insert into product_category (product_id,category_id)values('" . $p_id . "','" . $c_id . "')");
        }

        //using comma sepreted ids c_name select from category table
        $ids = implode(",", $category);
        $query_c = mysqli_query($con, "select c_name from category where c_id in ($ids)");

        //one by one c_name get from $query and store in one array variable
        while ($row = mysqli_fetch_assoc($query_c)) {
            $c_name[] = $row['c_name'];
        }

        //fetched array converted into comma sepreted value and pass into json
        $c_name = implode(',', $c_name);

        //pass the json data to ajax
        $data = array('result' => 'success', 'p_id' => $p_id, 'p_name' => $p_name, 'p_code' => $p_code, 'c_name' => $c_name);
        echo json_encode($data);
    }
    //category is unselected then execute belove code
    else {
        $c_name = "";
        //pass the json data to ajax
        $data = array('result' => 'success', 'p_id' => $p_id, 'p_name' => $p_name, 'p_code' => $p_code, 'c_name' => $c_name);
        echo json_encode($data);
    }
}
//name is blank then execute belove code
else {
    $ename = "name is required";
    $data = array('message' => $ename);
    echo json_encode($data);
}
?>


edit.php


<?php
include "conn.php";
?>
<?php  
$ids=$_POST['edit_id'];   //get the id of selected table row edit button
$c_id = array();
//get p_name & p_code from product database using specific table row id and store into $p_name & $p_code variable
$query_p = mysqli_query ($con, "SELECT p_name, p_code  FROM Product where p_id = '".$ids."'");
while($row = mysqli_fetch_assoc($query_p))     
{
$p_name = $row['p_name'];
$p_code = $row['p_code'];
}
//get category id from product_category database using specific table row id and store into $c_id array variable
$query_pc = mysqli_query($con,"SELECT category_id FROM product_category where product_id = '".$ids."'");
while($row = mysqli_fetch_assoc($query_pc))     
{
$c_id[] = $row['category_id'];
}
//if category is get from database
if(!empty($c_id))
{
//array($c_id) converted into comma sepreted category id and store into $c_id
$c_id = implode(',',$c_id);
//pass the json data to ajax
$data = array('result' => 'success', 'p_name' => $p_name, 'p_code' => $p_code, 'c_id' => $c_id);
echo json_encode($data);
}
//if category is not get from database
else{
//pass the json data to ajax
$data = array('p_name' => $p_name, 'p_code' => $p_code);
echo json_encode($data);
}
?>


update.php


<?php
include "conn.php";
?>
<?php 
//name is set then execute belove code 
if(!empty($_POST['name'])) 
{
$p_name=$_POST['name'];
$p_code=$_POST['code'];
$ids=$_POST['update_id'];   //get click edit button row id from form custom attribute update_id(get from ajax header)
//update value in product table(name,code) using ids
mysqli_query($con, "update product set p_name = '$p_name',p_code = '$p_code' where p_id = '".$ids."'");
//delete all old category value from product_category table using ids
mysqli_query($con,"delete from product_category where product_id = $ids");
//category is selected then execute belove code
if(!empty($_POST['cat']))
{
$category=$_POST['cat'];
$c_name = array();
//insert new selected category in product_category table using ids
foreach($category as $cid => $c_id)
{
                            mysqli_query($con,"insert into product_category (product_id,category_id)values('".$ids."','".$c_id."')");
}
//using comma sepreted id c_name select from category table
$ids = implode(",",$category);
$query_c = mysqli_query($con,"select c_name from category where c_id in ($ids)");
//one by one c_name get from $query and store in one array variable
while($row = mysqli_fetch_assoc($query_c))     
{
$c_name[] = $row['c_name'];
}
//fetched array converted into comma sepreted value and pass into json
$c_name = implode(',',$c_name);
//pass the json data to ajax
$data = array('result'=>'success', 'p_name' => $p_name, 'p_code' => $p_code, 'c_name' => $c_name);
echo json_encode($data);
}
//category is unselected then execute belove code
else{
$c_name = "";
//pass the json data to ajax
$data = array('result'=>'success', 'p_name' => $p_name, 'p_code' => $p_code, 'c_name' => $c_name);
echo json_encode($data); 
}
}
//name is blank then execute belove code
else{
$ename = "name is required";
$data = array('message' => $ename);
echo json_encode($data);
}
?>

delete.php


<?php 
include "conn.php";
?>
<?php
//get the id of selected table row delete button
$ids=$_POST['del_id'];
//delete data in product table(name,code) and also delete on product_category table
mysqli_query($con, "delete from product where p_id='".$ids."'");
?>

transaction.js


$(document).ready(function () {
//view data on table row from database
    $.ajax({
        url: "view.php",
        type: "POST",
        contentType: "application/json",
        success: function (jsonStr)
        {
            var obj = jQuery.parseJSON(jsonStr);
            var new_row = '';
            $.each(obj, function (index, value) {
                new_row = "<tr id=" + value.p_id + ">" +
                        "<td>" + "<button id='edit' editId=" + value.p_id + " name='edit' type='button' class='btn btn-primary btn-sm'><span class='glyphicon glyphicon-pencil'></span>&nbsp&nbspEdit</button>" + "</td>" +
                        "<td>" + "<button id='delete' deleteId=" + value.p_id + " name='delete' type='button' class='btn btn-primary btn-sm'><span class='glyphicon glyphicon-remove-circle'></span>&nbsp&nbspDELETE</button>" + "</td>" +
                        "<td id='name'>" + value.p_name + "</td>" +
                        "<td id='code'>" + value.p_code + "</td>" +
                        "<td id='c_name'>" + value.c_name + "</td></tr>";
                $("#display").append(new_row);
            });
        }
    });
    //click on add button new row add on table as well as add record in database
    $(document).on("click", "#add", function () {
        var form1 = $("#product").serialize();
        $.ajax({
            type: "POST",
            url: "insert.php",
            data: form1,
            dataType: "json",
            success: function (jsonStr) {
                if (jsonStr.result == 'success')
                {
                    $('#error').empty();
                    var new_row = '';
                    new_row = "<tr id=" + jsonStr.p_id + ">" +
                            "<td>" + "<button id='edit' editId=" + jsonStr.p_id + " name='edit' type='button' class='btn btn-primary btn-sm'><span class='glyphicon glyphicon-pencil'></span>&nbsp&nbspEdit</button>" + "</td>" +
                            "<td>" + "<button id='delete' deleteId=" + jsonStr.p_id + " name='delete' type='button' class='btn btn-primary btn-sm'><span class='glyphicon glyphicon-remove-circle'></span>&nbsp&nbspDELETE</button>" + "</td>" +
                            "<td>" + jsonStr.p_name + "</td>" +
                            "<td>" + jsonStr.p_code + "</td>" +
                            "<td>" + jsonStr.c_name + "</td></tr>";
                    $("#display tr:last").after(new_row);
                } else {
                    $('#error').html(jsonStr.message);
                }
            }
        });
    });
    //click on update button updated row display on table and also update in database
    $(document).on("click", "#UPDATE", function () {
        var update_id = $("#product[update_id]").attr("update_id"); //get custom attribute value from form
        $.ajax({
            type: "POST",
            url: "update.php",
            data: $("#product").serialize() + "&update_id=" + update_id,
            dataType: "json",
            success: function (jsonStr) {
                if (jsonStr.result == 'success')
                {
                    $('#error').empty();
                    var new_row = '';
                    new_row = "<tr id=" + update_id + ">" +
                            "<td>" + "<button id='edit' editId=" + update_id + " name='edit' type='button' class='btn btn-primary btn-sm'><span class='glyphicon glyphicon-pencil'></span>&nbsp&nbspEdit</button>" + "</td>" +
                            "<td>" + "<button id='delete' deleteId=" + update_id + " name='delete' type='button' class='btn btn-primary btn-sm'><span class='glyphicon glyphicon-remove-circle'></span>&nbsp&nbspDELETE</button>" + "</td>" +
                            "<td>" + jsonStr.p_name + "</td>" +
                            "<td>" + jsonStr.p_code + "</td>" +
                            "<td>" + jsonStr.c_name + "</td></tr>";
                    $('#display').find('#' + update_id).replaceWith(new_row);
                    $("#UPDATE").html("ADD"); //use for change name of UPDATE button
                    $("#UPDATE").attr("id", "add"); //use for change id of UPDATE button
                } else {
                    $('#error').html(jsonStr.message);
                }
            }
        });
    });
    //click on reset button clear form and custom attribute
    $(document).on('click', '#resetform', function () {
        $("#product").removeAttr("update_id");
    });
    //click on edit button particular row data fill on form
    $(document).on('click', '#edit', function () {
        var editId = $(this).closest("tr").attr("id");
        $("#add").off("click"); //use for stop add button click event
        $("#add").html("UPDATE"); //use for change name of add button
        $("#add").attr("id", "UPDATE"); //use for change id of add button
        $("#product").attr("update_id", editId); //set custom attribute update_id value using form id
        $.ajax({
            type: "POST",
            url: "edit.php",
            data: {edit_id: editId},
            dataType: "json",
            success: function (jsonStr) {
                //clicked edit button id row data fill on form field
                $("#name").val(jsonStr.p_name);
                $("#code").val(jsonStr.p_code);
                $('input[type="checkbox"]:checked').prop('checked', false); //before check new checkbox value old value remove
                if (jsonStr.result == 'success')
                {
                    $.each(jsonStr.c_id.split(','), function (_, val) {
                        $(':input[value=' + val + ']').prop("checked", true);
                    });
                } else
                {
                    $('input[type="checkbox"]:checked').prop('checked', false);
                }
            }
        });
    });
    //click on delete button particular row delete on form table
    $(document).on('click', '#delete', function () {
        var deleteId = $(this).closest("tr").attr("id");
        $.ajax({
            type: "POST",
            url: "delete.php",
            data: {del_id: deleteId},
            success: function (data) {
                $("#" + deleteId).remove();
            }
        });
    });
});


Thursday, 19 January 2017

JAVASCRIPT

JAVASCRIPT
What is JavaScript?
JavaScript is a dynamic computer programming language. It is lightweight and most commonly used as a part of web pages, whose implementations allow client-side script to interact with the user and make dynamic pages. It is an interpreted programming language with object-oriented capabilities.

JavaScript was first known as LiveScript, but Netscape changed its name to JavaScript, possibly because of the excitement being generated by Java. JavaScript made its first appearance in Netscape 2.0 in 1995 with the name LiveScript. The general-purpose core of the language has been embedded in Netscape, Internet Explorer, and other web browsers.

ü The ECMA-262 Specification defined a standard version of the core JavaScript language.
ü JavaScript is a lightweight, interpreted programming language.
ü Designed for creating network-centric applications.
ü Complementary to and integrated with Java.
ü Open and cross-platform


Client-side JavaScript
Client-side JavaScript is the most common form of the language. The script should be included in or referenced by an HTML document for the code to be interpreted by the browser.
It means that a web page need not be a static HTML, but can include programs that interact with the user, control the browser, and dynamically create HTML content.
The JavaScript client-side mechanism provides many advantages over traditional CGI server-side scripts. For example, you might use JavaScript to check if the user has entered a valid e-mail address in a form field.
The JavaScript code is executed when the user submits the form, and only if all the entries are valid, they would be submitted to the Web Server.
JavaScript can be used to trap user-initiated events such as button clicks, link navigation, and other actions that the user initiates explicitly or implicitly.





Advantages of JavaScript
The merits of using JavaScript are −
Less server interaction − You can validate user input before sending the page off to the server. This saves server traffic, which means less load on your server.
Immediate feedback to the visitors − They don't have to wait for a page reload to see if they have forgotten to enter something.
Increased interactivity − You can create interfaces that react when the user hovers over them with a mouse or activates them via the keyboard.
Richer interfaces − You can use JavaScript to include such items as drag-and-drop components and sliders to give a Rich Interface to your site visitors.

Limitations of JavaScript

We cannot treat JavaScript as a full-fledged programming language. It lacks the following important features −
ü Client-side JavaScript does not allow the reading or writing of files. This has been kept for security reason.
ü JavaScript cannot be used for networking applications because there is no such support available.
ü JavaScript doesn't have any multithreading or multiprocessor capabilities.
ü Once again, JavaScript is a lightweight, interpreted programming language that allows you to build interactivity into otherwise static HTML pages.

Why we use JavaScript?

       JavaScript is most commonly used as a client side scripting language. This means that JavaScript code is written into an HTML page. When a user requests an HTML page with JavaScript in it, the script is sent to the browser and it's up to the browser to do something with it.

JavaScript Can Change HTML Content:

       One of many JavaScript HTML methods is getElementById().

This example uses the method to "find" an HTML element (with id="demo") and changes the element content (innerHTML) to "Hello JavaScript":




<!DOCTYPE html>
<html>
<body>

<h1>What Can JavaScript Do?</h1>

<p id="demo">JavaScript can change HTML content.</p>

<button type="button" onclick="document.getElementById('demo').innerHTML = 'Hello JavaScript!'">Click Me!</button>

</body>
</html>





EXAMPLE:
<!DOCTYPE html>
<html>
<body>
<h1>What Can JavaScript Do?</h1>

<p id="demo">JavaScript can change HTML content.</p>

<button type="button" onclick="document.getElementById('demo').innerHTML = 'Hello JavaScript!'">Change HTML content</button>

<button onclick="document.getElementById('myImage').src='pic_bulbon.gif'">Turn on the light</button>
<img id="myImage" src="pic_bulboff.gif" style="width:100px">
<button onclick="document.getElementById('myImage').src='pic_bulboff.gif'">Turn off the light</button>

<button type="button" onclick="document.getElementById('demo').style.fontSize='35px'"> Change HTML Styles</button>

<button type="button" onclick="document.getElementById('demo').style.display='none'">Hide HTML Elements</button>

<button type="button" onclick="document.getElementById('demo').style.display='block'">Hide HTML Elements</button>

</body>
</html>






JavaScript Where To:
In HTML, JavaScript code must be inserted between <script> and </script> tags.

<script>
                    document.getElementById("demo").innerHTML = "My First JavaScript";
</script>

JavaScript Functions and Events:

A JavaScript function is a block of JavaScript code, that can be executed when "asked" for.

For example, a function can be executed when an event occurs, like when the user clicks a button.




JavaScript in <head> or <body>:

ü You can place any number of scripts in an HTML document.
ü Scripts can be placed in the <body>, or in the <head> section of an HTML page, or in both.

JavaScript in <head>:

In this example, a JavaScript function is placed in the <head> section of an HTML page.
The function is invoked (called) when a button is clicked:

<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>
<body>
<h1>A Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
</body>
</html>

JavaScript in <body>:

In this example, a JavaScript function is placed in the <body> section of an HTML page.
The function is invoked (called) when a button is clicked:

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>A Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>

<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</body>
</html>

External JavaScript:
Scripts can also be placed in external files:
External file: myScript.js
function myFunction() {
   document.getElementById("demo").innerHTML = "Paragraph changed.";
}       
ü External scripts are practical when the same code is used in many different web pages.
ü JavaScript files have the file extension .js.
ü To use an external script, put the name of the script file in the src (source) attribute of a <script> tag:

<!DOCTYPE html>
<html>
<body>

<h1>External JavaScript</h1>

<p id="demo">A Paragraph.</p>

<button type="button" onclick="myFunction()">Try it</button>

<p>(myFunction is stored in an external file called "myScript.js")</p>

<script src="myScript.js"></script>

</body>
</html>



ü You can place an external script reference in <head> or <body> as you like.

ü The script will behave as if it was located exactly where the <script> tag is located.

NOTE: External scripts cannot contain <script> tags.

External JavaScript Advantages:

Placing scripts in external files has some advantages:

ü It separates HTML and code
ü It makes HTML and JavaScript easier to read and maintain
ü Cached JavaScript files can speed up page loads
ü To add several script files to one page  - use several script tags:

EXAMPLE:

<script src="myScript1.js"></script>
<script src="myScript2.js"></script>
External References:

ü External scripts can be referenced with a full URL or with a path relative to the current web page.

This example uses a full URL to link to a script:
<script      
                      src="http://www.w3schools.com/js/myScript1.js">
</script>

This example uses a script located in a specified folder on the current web site:
<script src="/js/myScript1.js"></script>

This example links to a script located in the same folder as the current page:
<script src="myScript.js"></script>



Friday, 29 July 2016

Hybrid

“Hybrid framework is the most commonly used framework in test automation projects.”

So, if you learn this and get it right, then you would be in a position to work on automation projects in your organization. With this, let us now start with the basics of the QTP hybrid framework.


What is Hybrid Framework in QTP?

Each and every framework type in QTP has its own positives and negatives. You can take the positive points from each of these frameworks and create a customized framework that suites your requirements. This customized framework is called a hybrid framework.

So, in very simple terms – “A hybrid framework is a framework that is created by combining together the features of the different types of QTP frameworks.” This is depicted in the image shown below.

Hybrid Framework In QTP
Is there any specific predefined structure of a Hybrid Framework?

Well, a straightforward answer for this question would be – No. Let try to understand why it is this way? In the previous section, you had read about what a hybrid framework actually is. There are two key takeaway points in that explanation –

    1) A hybrid framework is a collection of features from the other framework types.
    2) A hybrid framework is one that suites your requirements.


Now, the second point mentioned above is very important. The hybrid framework that you create should suite your requirements or your stakeholder’s requirements. And there can be a lot of factors that influence your decisions. For example –

    – you might want to use a particular feature in your hybrid framework but it might not be useful or necessary for the application you are testing. Example – you might want to use excel sheets to store test data. But in case your application takes the same data every time, it makes more sense to hard-code the data in your code itself or maybe taking it as environment variables
    – you might have a disliking for certain features and hence you always tend to use the features that you like. For example, I’m more biased towards functions and hence I tend to use them more than say, using action calls
    – your client may have a preference towards certain type of framework as they would have seen a similar sort of framework being used previously. So if you can convince the client, then its well and good, else you would have to stick around with what they have suggested (this is something that I have had to deal with in few of my automation projects)


Taking all the above points into consideration, you can safely say that the features that you select to create your hybrid framework may vary vastly from someone else’s framework. And hence, there is no predefined structure of this type of framework. To sum it up, different hybrid frameworks should be like –

How different hybrid frameworks in QTP differ from each other

But there are certain components (or features) that frequently appear in different hybrid frameworks. These components would be the ones that we would use to create the sample hybrid framework.

Is it easy to identify Hybrid Frameworks?

Well, its easy but not that straightforward to identify a hybrid framework. An important reason for this is that the implementation of hybrid framework varies from person to person and from project to project. But you had also seen in the beginning of this article that most of the frameworks implemented in live projects are in fact hybrid frameworks.

Hence, any good framework worth its salt should be a hybrid framework. And to identify it properly, you need to have a close look at its architecture and its components. You should try to find out if its using keywords extensively, or if its taking its data from excel sheets, or if the code is written in modular format. This way, you would be able to identify the framework types from which the hybrid framework borrows its features.


Useful Tip: Whenever you create or use a hybrid framework, don’t just call it a hybrid framework. Always try to include the names of the other frameworks from which your hybrid framework has derived its features. For example, you can call your framework as –

    – a hybrid framework based on functional and data driven approach
    – a keyword based hybrid framework
    – a hybrid framework implemented with functional and keyword driven components
    – or any other fancy terms that come to your mind

Its always considered a good practice to call your framework this way.


A word about BPT Framework: A good BPT framework will also not just be a BPT framework alone. It would also incorporate the features of a keyword driven, data driven or modular framework in it. And if that’s the case, then it becomes a hybrid framework. But still people tend to call it a BPT framework. So in your case, you can choose to simply call it a BPT framework, or a BPT based hybrid framework or something on similar lines.


Features of a Hybrid Framework

In this section, you would see some of the features that you can be implemented as part of your hybrid framework. Some of these features are pretty common and you would see them being used in many different hybrid frameworks. There would be other features also that are not so important and can be termed as nice to have (but not mandatory). Let us see some of these important features.


1.) The most basic set of features come first. The hybrid framework should be designed in such a way that it is re-usable and easily scalable. Also, the code should be easy to understand and maintain. As a matter of fact, please don’t consider this point as a feature. It is a must-have and you should consider it a rule. Doing this would save you a lot of troubles afterwards.


2.) All the components in the framework can be grouped separately. You can employ a basic folder structure to keep the test cases, function libraries, data sheets and test results grouped together in an efficient manner.

employ an efficient folder structure for your framework


3.) One click execution. This is a good feature that you can implement in your automation framework. With just a single click of a button, the framework should execute all the test cases. In most of the cases, this feature is implement using MS excel + macros. This is because the excel sheets provide you with more control on how you can select your test cases.

One Click Execution Of Test Scripts


4.) Another important point is how you display your test results. You should aim to display the test results at minimum 2 different levels of abstraction. These are – summarized report and detailed report. A summarized report can simply be an excel sheet that provides the list of the test cases that were executed, whether they passed or failed, and a link pointing towards the detailed report for each of  the test cases. You can also add more parameters to this report if required. An example of a summarized report is shown in the below image.

Summarized Report

A detailed report would be the actual QTP result which you would have saved in appropriate result folders. The detailed report will mostly be used for investigative purpose. For example, in case a test script fails, or it takes more than expected time for completion, you can open the detailed result and try to find out the exact cause for the issue.


5.) Automated Email Notification. This is another important feature that you can incorporate in your automation framework. This is especially useful when you execute your test scripts in batch execution mode. You can write some logic in your framework that will automatically send emails to intended recipients after the completion of the batch run. You can also include the summarized excel report as an attachment in the email.


6.) Automated SMS Notification. This can be considered as an extension of the above point. Here, you can have your framework send an SMS to a select list of people with the test execution status.

If you intend to use this feature, then please keep in mind that the messages that you send should be short and crisp. For example, you could send something like this as an SMS – “TCs executed-100. Passed-85. Failed-15.”

Also, please note that this feature is used very rarely. So from the usability point of view, its very difficult justify the use or need of sending SMSes. Also you would need to factor in the cost of sending SMSes.

A scenario where sending SMS can be useful: You can configure your framework to send an SMS to certain people when, say 5 or 10 consecutive test cases fail one after the other. Such a scenario normally indicates that there is some big issue going on. Maybe the environment went down, or some other problem. Having an SMS sent in such a situation can help the teams identify the issue in a more timely manner.


7.) Framework should be externally configurable to a certain extent. This is a nice feature that I have started using recently. The idea behind this feature is – there should be certain functionalities in your framework that you should be able to configure without having to touch the code. Consider the following scenarios as examples –

    a) Consider a case that on a particular day, the test environment is pretty slow. This requires you to increase the default load time of the pages. Your framework should provide a provision to do this easily for all the test cases.
    b) Consider another situation where you need to modify the details of the people to whom the email should be sent. Or maybe you don’t want to send email for a particular batch run. You framework should provide you a means with which you should be able to do these tasks without touching the code.

The best way to create an externally configurable sheet is to use an excel sheet. The below image shows an example of such a sheet.

Hybrid Framework - External Configuration Sheet


8.) Intermediate Status Reports. This is another nice to have feature that you can incorporate in your automation framework. Consider a scenario where you have set up a batch execution of 100 test cases. Its obvious that you wouldn’t be sitting in front of your system all the time to monitor the execution. Suppose you move away from your desk and come back to see the execution after say, 1 hour.

At this point the test cases might still be executing but you would not know how much more time your scripts will take to execute or maybe how many test cases are still pending. In such situations, intermediate status reports come in handy.

Intermediate status report can be as simple as a auto-closing popup that appears after the execution of each test case, gives you the updates and closes automatically (in 3 to 5 seconds). A simple message like the one shown below will be more than enough.

Intermediate Status Report

These were some of the features that you can incorporate in your automation framework. It’s not necessary that you add all the features at once. A good approach would be create the framework with the minimum necessary features. And then you can add these nice-to-have features to your framework as enhancements.

In the upcoming articles in this series, we will create a hybrid framework from scratch where we will be incorporating some of these features. Please note that we will not be adding all the features to the sample framework as it leads to code complexity. The goal of the upcoming articles would be to keep the framework creation process as simple as possible, so that it is easily understood by everyone.

Wednesday, 20 April 2016

AngularJS

AngularJS Introduction


AngularJS is a JavaScript framework. It can be added to an HTML page with a <script> tag.
AngularJS extends HTML attributes with Directives, and binds data to HTML with Expressions.

AngularJS is a JavaScript Framework

AngularJS is a JavaScript framework. It is a library written in JavaScript.
AngularJS is distributed as a JavaScript file, and can be added to a web page with a script tag:
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

AngularJS Extends HTML

AngularJS extends HTML with ng-directives.
The ng-app directive defines an AngularJS application.
The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.
The ng-bind directive binds application data to the HTML view.

AngularJS Example

<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>

<div ng-app="">
  <p>Name: <input type="text" ng-model="name"></p>
  <p ng-bind="name"></p>
</div>

</body>
</html>
Example explained:
AngularJS starts automatically when the web page has loaded.
The ng-app directive tells AngularJS that the <div> element is the "owner" of an AngularJS application.
The ng-model directive binds the value of the input field to the application variable name.
The ng-bind directive binds the innerHTML of the <p> element to the application variable name.

AngularJS Directives

As you have already seen, AngularJS directives are HTML attributes with an ng prefix.
The ng-init directive initializes AngularJS application variables.

AngularJS Example

<div ng-app="" ng-init="firstName='John'">

<p>The name is <span ng-bind="firstName"></span></p>

</div>
Alternatively with valid HTML:

AngularJS Example

<div data-ng-app="" data-ng-init="firstName='John'">

<p>The name is <span data-ng-bind="firstName"></span></p>

</div>
Note You can use data-ng-, instead of ng-, if you want to make your page HTML valid.
You will learn a lot more about directives later in this tutorial.

AngularJS Expressions

AngularJS expressions are written inside double braces: {{ expression }}.
AngularJS will "output" data exactly where the expression is written:

AngularJS Example

<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>

<div ng-app="">
  <p>My first expression: {{ 5 + 5 }}</p>
</div>

</body>
</html>
AngularJS expressions bind AngularJS data to HTML the same way as the ng-bind directive.

AngularJS Example

<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>

<div ng-app="">
  <p>Name: <input type="text" ng-model="name"></p>
  <p>{{name}}</p>
</div>

</body>
</html>
You will learn more about expressions later in this tutorial.

AngularJS Applications

AngularJS modules define AngularJS applications.
AngularJS controllers control AngularJS applications.
The ng-app directive defines the application, the ng-controller directive defines the controller.

AngularJS Example

<div ng-app="myApp" ng-controller="myCtrl">

First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{firstName + " " + lastName}}

</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.firstName= "John";
    $scope.lastName= "Doe";
});
</script>
AngularJS modules define applications:

AngularJS Module

var app = angular.module('myApp', []);
AngularJS controllers control applications:

AngularJS Controller

app.controller('myCtrl', function($scope) {
    $scope.firstName= "John";
    $scope.lastName= "Doe";
}); 

AngularJS Expressions


AngularJS binds data to HTML using Expressions.

AngularJS Expressions

AngularJS expressions can be written inside double braces: {{ expression }}.
AngularJS expressions can also be written inside a directive: ng-bind="expression".
AngularJS will resolve the expression, and return the result exactly where the expression is written.
AngularJS expressions are much like JavaScript expressions: They can contain literals, operators, and variables.
Example {{ 5 + 5 }} or {{ firstName + " " + lastName }}

Example

<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>

<div ng-app="">
  <p>My first expression: {{ 5 + 5 }}</p>
</div>

</body>
</html>
If you remove the ng-app directive, HTML will display the expression as it is, without solving it:

Example

<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>

<div>
  <p>My first expression: {{ 5 + 5 }}</p>
</div>

</body>
</html>
You can write expressions wherever you like, AngularJS will simply resolve the expression and return the result.
Example: Let AngularJS change the value of CSS properties.
Change the color of the input box below, by changing it's value:

Example

<div ng-app="" ng-init="myCol='lightblue'">

<input style="background-color:{{myCol}}" ng-model="myCol" value="{{myCol}}">

</div>

AngularJS Numbers

AngularJS numbers are like JavaScript numbers:

Example

<div ng-app="" ng-init="quantity=1;cost=5">

<p>Total in dollar: {{ quantity * cost }}</p>

</div>
Same example using ng-bind:

Example

<div ng-app="" ng-init="quantity=1;cost=5">

<p>Total in dollar: <span ng-bind="quantity * cost"></span></p>

</div>
Note Using ng-init is not very common. You will learn a better way to initialize data in the chapter about controllers.

AngularJS Strings

AngularJS strings are like JavaScript strings:

Example

<div ng-app="" ng-init="firstName='John';lastName='Doe'">

<p>The name is {{ firstName + " " + lastName }}</p>

</div>
Same example using ng-bind:

Example

<div ng-app="" ng-init="firstName='John';lastName='Doe'">

<p>The name is <span ng-bind="firstName + ' ' + lastName"></span></p>

</div>

AngularJS Objects

AngularJS objects are like JavaScript objects:

Example

<div ng-app="" ng-init="person={firstName:'John',lastName:'Doe'}">

<p>The name is {{ person.lastName }}</p>

</div>
Same example using ng-bind:

Example

<div ng-app="" ng-init="person={firstName:'John',lastName:'Doe'}">

<p>The name is <span ng-bind="person.lastName"></span></p>

</div>

AngularJS Arrays

AngularJS arrays are like JavaScript arrays:

Example

<div ng-app="" ng-init="points=[1,15,19,2,40]">

<p>The third result is {{ points[2] }}</p>

</div>
Same example using ng-bind:

Example

<div ng-app="" ng-init="points=[1,15,19,2,40]">

<p>The third result is <span ng-bind="points[2]"></span></p>

</div>

AngularJS Expressions vs. JavaScript Expressions

Like JavaScript expressions, AngularJS expressions can contain literals, operators, and variables.
Unlike JavaScript expressions, AngularJS expressions can be written inside HTML.
AngularJS expressions do not support conditionals, loops, and exceptions, while JavaScript expressions do.
AngularJS expressions support filters, while JavaScript expressions do not.

AngularJS Modules


An AngularJS module defines an application.
The module is a container for the different parts of an application.
The module is a container for the application controllers.
Controllers always belong to a module.

Creating a Module

A module is created by using the AngularJS function angular.module
<div ng-app="myApp">...</div>

<script>

var app = angular.module("myApp", []);
</script>
The "myApp" parameter refers to an HTML element in which the application will run.
Now you can add controllers, directives, filters, and more, to your AngularJS application.

Adding a Controller

Add a controller to your application, and refer to the controller with the ng-controller directive:

Example

<div ng-app="myApp" ng-controller="myCtrl">
{{ firstName + " " + lastName }}
</div>

<script>
var app = angular.module("myApp", []);

app.controller("myCtrl", function($scope) {
    $scope.firstName = "John";
    $scope.lastName = "Doe";
});
</script>
You will learn more about controllers later in this tutorial.

Adding a Directive

AngularJS has a set of built-in directives which you can use to add functionality to your application.
For a full reference, visit our AngularJS directive reference.
In addition you can use the module to add your own directives to your applications:

Example

<div ng-app="myApp" w3-test-directive></div>

<script>

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

app.directive("w3TestDirective", function() {
    return {
        template : "I was made in a directive constructor!"
    };
});
</script>
You will learn more about directives later in this tutorial.

Modules and Controllers in Files

It is common in AngularJS applications to put the module and the controllers in JavaScript files.
In this example, "myApp.js" contains an application module definition, while "myCtrl.js" contains the controller:

Example

<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">
{{ firstName + " " + lastName }}
</div>

<script src="myApp.js"></script>
<script src="myCtrl.js"></script>

</body>
</html>

myApp.js

var app = angular.module("myApp", []);
Note The [] parameter in the module definition can be used to define dependent modules.
Note Without the [] parameter, you are not creating a new module, but retrieving an existing one.

myCtrl.js

app.controller("myCtrl", function($scope) {
    $scope.firstName = "John";
    $scope.lastName= "Doe";
});

Functions can Pollute the Global Namespace

Global functions should be avoided in JavaScript. They can easily be overwritten or destroyed by other scripts.
AngularJS modules reduces this problem, by keeping all functions local to the module.

When to Load the Library

While it is common in HTML applications to place scripts at the end of the <body> element, it is recommended that you load the AngularJS library either in the <head> or at the start of the <body>.
This is because calls to angular.module can only be compiled after the library has been loaded.

Example

<!DOCTYPE html>
<html>
<body>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

<div ng-app="myApp" ng-controller="myCtrl">
{{ firstName + " " + lastName }}
</div>

<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
    $scope.firstName = "John";
    $scope.lastName = "Doe";
});
</script>

</body>
</html>

AngularJS Directives


AngularJS lets you extend HTML with new attributes called Directives.
AngularJS has a set of built-in directives which offers functionality to your applications.
AngularJS also lets you define your own directives.

AngularJS Directives

AngularJS directives are extended HTML attributes with the prefix ng-.
The ng-app directive initializes an AngularJS application.
The ng-init directive initializes application data.
The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.
Read about all AngularJS directives in our AngularJS directive reference.

Example

<div ng-app="" ng-init="firstName='John'">

<p>Name: <input type="text" ng-model="firstName"></p>
<p>You wrote: {{ firstName }}</p>

</div>
The ng-app directive also tells AngularJS that the <div> element is the "owner" of the AngularJS application.

Data Binding

The {{ firstName }} expression, in the example above, is an AngularJS data binding expression.
Data binding in AngularJS binds AngularJS expressions with AngularJS data.
{{ firstName }} is bound with ng-model="firstName".
In the next example two text fields are bound together with two ng-model directives:

Example

<div ng-app="" ng-init="quantity=1;price=5">

Quantity: <input type="number" ng-model="quantity">
Costs:    <input type="number" ng-model="price">

Total in dollar: {{ quantity * price }}

</div>
Note Using ng-init is not very common. You will learn how to initialize data in the chapter about controllers.

Repeating HTML Elements

The ng-repeat directive repeats an HTML element:

Example

<div ng-app="" ng-init="names=['Jani','Hege','Kai']">
  <ul>
    <li ng-repeat="x in names">
      {{ x }}
    </li>
  </ul>
</div>
The ng-repeat directive actually clones HTML elements once for each item in a collection.
The ng-repeat directive used on an array of objects:

Example

<div ng-app="" ng-init="names=[
{name:'Jani',country:'Norway'},
{name:'Hege',country:'Sweden'},
{name:'Kai',country:'Denmark'}]"
>

<ul>
  <li ng-repeat="x in names">
    {{ x.name + ', ' + x.country }}
  </li>
</ul>

</div>
Note AngularJS is perfect for database CRUD (Create Read Update Delete) applications.
Just imagine if these objects were records from a database.

The ng-app Directive

The ng-app directive defines the root element of an AngularJS application.
The ng-app directive will auto-bootstrap (automatically initialize) the application when a web page is loaded.

The ng-init Directive

The ng-init directive defines initial values for an AngularJS application.
Normally, you will not use ng-init. You will use a controller or module instead.
You will learn more about controllers and modules later.

The ng-model Directive

The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.
The ng-model directive can also:
  • Provide type validation for application data (number, email, required).
  • Provide status for application data (invalid, dirty, touched, error).
  • Provide CSS classes for HTML elements.
  • Bind HTML elements to HTML forms.
Read more about the ng-model directive in the next chapter.

Create New Directives

In addition to all the built-in AngularJS directives, you can create your own directives.
New directives are created by using the .directive function.
To invoke the new directive, make an HTML element with the same tag name as the new directive.
When naming a directive, you must use a camel case name, w3TestDirective, but when invoking it, you must use - separated name, w3-test-directive:

Example

<body ng-app="myApp">

<w3-test-directive></w3-test-directive>

<script>
var app = angular.module("myApp", []);
app.directive("w3TestDirective", function() {
    return {
        template : "<h1>Made by a directive!</h1>"
    };
});
</script>

</body>
You can invoke a directive by using:
  • Element name
  • Attribute
  • Class
  • Comment
The examples below will all produce the same result:
Element name
<w3-test-directive></w3-test-directive>
Attribute
<div w3-test-directive></div>
Class
<div class="w3-test-directive"></div>
Comment
<!-- directive: w3-test-directive -->

Restrictions

You can restrict your directives to only be invoked by some of the methods.

Example

By adding a restrict property with the value "A", the directive can only be invoked by attributes:
var app = angular.module("myApp", []);
app.directive("w3TestDirective", function() {
    return {
        restrict : "A",
        template : "<h1>Made by a directive!</h1>"
    };
});




AngularJS ng-model Directive


The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.

The ng-model Directive

With the ng-model directive you can bind the value of an input field to a variable created in AngularJS.

Example

<div ng-app="myApp" ng-controller="myCtrl">
    Name: <input ng-model="name">
</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.name = "John Doe";
});
</script>

Two-Way Binding

The binding goes both ways. If the user changes the value inside the input field, the AngularJS property will also change it's value:

Example

<div ng-app="myApp" ng-controller="myCtrl">
    Name: <input ng-model="name">
    <h1>You entered: {{name}}</h1>
</div>

Validate User Input

The ng-model directive can provide type validation for application data (number, e-mail, required):

Example

<form ng-app="" name="myForm">
    Email:
    <input type="email" name="myAddress" ng-model="text">
    <span ng-show="myForm.myAddress.$error.email">Not a valid e-mail address</span>
</form>
In the example above, the span will be displayed only if the expression in the ng-show attribute returns true.
Note If the property in the ng-model attribute does not exist, AngularJS will create one for you.

Application Status

The ng-model directive can provide status for application data (invalid, dirty, touched, error):

Example

<form ng-app="" name="myForm" ng-init="myText = 'post@myweb.com'">
    Email:
    <input type="email" name="myAddress" ng-model="myText" required>
    <h1>Status</h1>
    {{myForm.myAddress.$valid}}
    {{myForm.myAddress.$dirty}}
    {{myForm.myAddress.$touched}}
</form>

CSS Classes

The ng-model directive provides CSS classes for HTML elements, depending on their status:

Example

<style>
input.ng-invalid {
    background-color: lightblue;
}
</style>
<body>

<form ng-app="" name="myForm">
    Enter your name:
    <input name="myAddress" ng-model="text" required>
</form>
The ng-model directive adds/removes the following classes, according to the status of the form field:
  • ng-empty
  • ng-not-empty
  • ng-touched
  • ng-untouched
  • ng-valid
  • ng-invalid
  • ng-dirty
  • ng-pending
  • ng-pristine


AngularJS Data Binding


Data binding in AngularJS is the synchronization between the model and the view.

Data Model

AngularJS applications usually have a data model. The data model is a collection of data available for the application.

Example

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.firstname = "John";
    $scope.lastname = "Doe";
});

HTML View

The HTML container where the AngularJS application is displayed, is called the view.
The view has access to the model, and there are several ways of displaying model data in the view.
You can use the ng-bind directive, which will bind the innerHTML of the element to the specified model property:

Example

<p ng-bind="firstname"></p>
You can also use double braces {{ }} to display content from the model:

Example

<p>First name: {{firstname}}</p>
Or you can use the ng-model directive on HTML controls to bind the model to the view.

The ng-model Directive

Use the ng-model directive to bind data from the model to the view on HTML controls (input, select, textarea)

Example

<input ng-model="firstname">
The ng-model directive provides a two-way binding between the model and the view.

Two-way Binding

Data binding in AngularJS is the synchronization between the model and the view.
When data in the model changes, the view reflects the change, and when data in the view changes, the model is updated as well. This happens immediately and automatically, which makes sure that the model and the view is updated at all times.

Example

<div ng-app="myApp" ng-controller="myCtrl">
    Name: <input ng-model="firstname">
    <h1>{{firstname}}</h1>
</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.firstname = "John";
    $scope.lastname = "Doe";
});
</script>

AngularJS Controller

Applications in AngularJS are controlled by controllers. Read about controllers in the AngularJS Controllers chapter.
Because of the immediate synchronization of the model and the view, the controller can be completely separated from the view, and simply concentrate on the model data. Thanks to the data binding in AngularJS, the view will reflect any changes made in the controller.

Example

<div ng-app="myApp" ng-controller="myCtrl">
    <h1 ng-click="changeName()">{{firstname}}</h1>
</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.changeName = function() {
        $scope.firstname = "Nelly";
    }
});
</script>




AngularJS Controllers


AngularJS controllers control the data of AngularJS applications.
AngularJS controllers are regular JavaScript Objects.

AngularJS Controllers

AngularJS applications are controlled by controllers.
The ng-controller directive defines the application controller.
A controller is a JavaScript Object, created by a standard JavaScript object constructor.

AngularJS Example

<div ng-app="myApp" ng-controller="myCtrl">

First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{firstName + " " + lastName}}

</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.firstName = "John";
    $scope.lastName = "Doe";
});
</script>
Application explained:
The AngularJS application is defined by  ng-app="myApp". The application runs inside the <div>.
The ng-controller="myCtrl" attribute is an AngularJS directive. It defines a controller.
The myCtrl function is a JavaScript function.
AngularJS will invoke the controller with a $scope object.
In AngularJS, $scope is the application object (the owner of application variables and functions).
The controller creates two properties (variables) in the scope (firstName and lastName).
The ng-model directives bind the input fields to the controller properties (firstName and lastName).

Controller Methods

The example above demonstrated a controller object with two properties: lastName and firstName.
A controller can also have methods (variables as functions):

AngularJS Example

<div ng-app="myApp" ng-controller="personCtrl">

First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{fullName()}}

</div>

<script>
var app = angular.module('myApp', []);
app.controller('personCtrl', function($scope) {
    $scope.firstName = "John";
    $scope.lastName = "Doe";
    $scope.fullName = function() {
        return $scope.firstName + " " + $scope.lastName;
    };
});
</script>

Controllers In External Files

In larger applications, it is common to store controllers in external files.
Just copy the code between the <script> tags into an external file named personController.js:

AngularJS Example

<div ng-app="myApp" ng-controller="personCtrl">

First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{firstName + " " + lastName}}

</div>

<script src="personController.js"></script>

Another Example

For the next example we will create a new controller file:
angular.module('myApp', []).controller('namesCtrl', function($scope) {
    $scope.names = [
        {name:'Jani',country:'Norway'},
        {name:'Hege',country:'Sweden'},
        {name:'Kai',country:'Denmark'}
    ];
});
Save the file as  namesController.js:
And then use the controller file in an application:

AngularJS Example

<div ng-app="myApp" ng-controller="namesCtrl">

<ul>
  <li ng-repeat="x in names">
    {{ x.name + ', ' + x.country }}
  </li>
</ul>

</div>

<script src="namesController.js"></script>

AngularJS Scope


The scope is the binding part between the HTML (view) and the JavaScript (controller).
The scope is an object with the available properties and methods.
The scope is available for both the view and the controller.

How to Use the Scope?

When you make a controller in AngularJS, you pass the $scope object as an argument:

Example

Properties made in the controller, can be referred to in the view:
<div ng-app="myApp" ng-controller="myCtrl">

<h1>{{carname}}</h1>

</div>

<script>
var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope) {
    $scope.carname = "Volvo";
});
</script>
When adding properties to the $scope object in the controller, the view (HTML) gets access to these properties.
In the view, you do not use the prefix $scope, you just refer to a propertyname, like {{carname}}.

Understanding the Scope

If we consider an AngularJS application to consist of:
  • View, which is the HTML.
  • Model, which is the data available for the current view.
  • Controller, which is the JavaScript function that makes/changes/removes/controls the data.
Then the scope is the Model.
The scope is a JavaScript object with properties and methods, which are available for both the view and the controller.

Example

If you make changes in the view, the model and the controller will be updated:
<div ng-app="myApp" ng-controller="myCtrl">

<input ng-model="name">

<h1>My name is {{name}}</h1>

</div>

<script>
var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope) {
    $scope.name = "John Doe";
});
</script>

Know Your Scope

It is important to know which scope you are dealing with, at any time.
In the two examples above there is only one scope, so knowing your scope is not an issue, but for larger applications there can be sections in the HTML DOM which can only access certain scopes.

Example

When dealing with the ng-repeat directive, each repetition has access to the current repetition object:
<div ng-app="myApp" ng-controller="myCtrl">

<ul>
    <li ng-repeat="x in names">{{x}}</li>
</ul>

</div>

<script>
var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope) {
    $scope.names = ["Emil", "Tobias", "Linus"];
});
</script>
Each <li> element has access to the current repetition object, in this case a string, which is referred to by using x.

Root Scope

All applications have a $rootScope which is the scope created on the HTML element that contains the ng-app directive.
The rootScope is available in the entire application.
If a variable has the same name in both the current scope and in the rootScope, the application use the one in the current scope.

Example

A variable named "color" exists in both the controller's scope and in the rootScope:
<body ng-app="myApp">

<p>The rootScope's favorite color:</p>
<h1>{{color}}</h1>

<div ng-controller="myCtrl">
    <p>The scope of the controller's favorite color:</p>
    <h1>{{color}}</h1>
</div>

<p>The rootScope's favorite color is still:</p>
<h1>{{color}}</h1>

<script>
var app = angular.module('myApp', []);
app.run(function($rootScope) {
    $rootScope.color = 'blue';
});
app.controller('myCtrl', function($scope) {
    $scope.color = "red";
});
</script>
</body>

AngularJS Filters


Filters can be added in AngularJS to format data.

AngularJS Filters

AngularJS provides filters to transform data:
  • currency Format a number to a currency format.
  • date Format a date to a specified format.
  • filter Select a subset of items from an array.
  • json Format an object to a JSON string.
  • limitTo Limits an array/string, into a specified number of elements/characters.
  • lowercase Format a string to lower case.
  • number Format a number to a string.
  • orderBy Orders an array by an expression.
  • uppercase Format a string to upper case.

Adding Filters to Expressions

Filters can be added to expressions by using the pipe character |, followed by a filter.
The uppercase filter format strings to upper case:

Example

<div ng-app="myApp" ng-controller="personCtrl">

<p>The name is {{ lastName | uppercase }}</p>

</div>
The lowercase filter format strings to lower case:

Example

<div ng-app="myApp" ng-controller="personCtrl">

<p>The name is {{ lastName | lowercase }}</p>

</div>

Adding Filters to Directives

Filters are added to directives, like ng-repeat, by using the pipe character |, followed by a filter:

Example

The orderBy filter sorts an array:
<div ng-app="myApp" ng-controller="namesCtrl">

<ul>
  <li ng-repeat="x in names | orderBy:'country'">
    {{ x.name + ', ' + x.country }}
  </li>
</ul>

</div>

The currency Filter

The currency filter formats a number as currency:

Example

<div ng-app="myApp" ng-controller="costCtrl">

<h1>Price: {{ price | currency }}</h1>

</div>
Read more about the currency filter in our AngularJS currency Filter Reference

The filter Filter

The filter filter selects a subset of an array.
The filter filter can only be used on arrays, and it returns an array containing only the matching items.

Example

Return the names that contains the letter "i":
<div ng-app="myApp" ng-controller="namesCtrl">

<ul>
  <li ng-repeat="x in names | filter : 'i'">
    {{ x }}
  </li>
</ul>

</div>
Read more about the filter filter in our AngularJS filter Filter Reference

Filter an Array Based on User Input

By setting the ng-model directive on an input field, we can use the value of the input field as an expression in a filter.
Type a letter in the input field, and the list will shrink/grow depending on the match:

  • Jani
  • Carl
  • Margareth
  • Hege
  • Joe
  • Gustav
  • Birgit
  • Mary
  • Kai

Example

<div ng-app="myApp" ng-controller="namesCtrl">

<p><input type="text" ng-model="test"></p>

<ul>
  <li ng-repeat="x in names | filter : test">
    {{ x }}
  </li>
</ul>

</div>

Sort an Array Based on User Input

Click the table headers to change the sort order::
Name Country
Jani Norway
Carl Sweden
Margareth England
Hege Norway
Joe Denmark
Gustav Sweden
Birgit Denmark
Mary England
Kai Norway
By adding the ng-click directive on the table headers, we can run a function that changes the sorting order of the array:

Example

<div ng-app="myApp" ng-controller="namesCtrl">

<table border="1" width="100%">
  <tr>
    <th ng-click="orderByMe('name')">Name</th>
    <th ng-click="orderByMe('country')">Country</th>
  </tr>
  <tr ng-repeat="x in names | orderBy:myOrderBy">
    <td>{{x.name}}</td>
    <td>{{x.country}}</td>
  </tr>
</table>

</div>

<script>
angular.module('myApp', []).controller('namesCtrl', function($scope) {
  $scope.names = [
    {name:'Jani',country:'Norway'},
    {name:'Carl',country:'Sweden'},
    {name:'Margareth',country:'England'},
    {name:'Hege',country:'Norway'},
    {name:'Joe',country:'Denmark'},
    {name:'Gustav',country:'Sweden'},
    {name:'Birgit',country:'Denmark'},
    {name:'Mary',country:'England'},
    {name:'Kai',country:'Norway'}
  ];
  $scope.orderByMe = function(x) {
    $scope.myOrderBy = x;
  }
});
</script>

Custom Filters

You can make your own filters by registering a new filter factory function with your module:

Example

Make a custom filter called "myFormat":
<ul ng-app="myApp" ng-controller="namesCtrl">
    <li ng-repeat="x in names">
        {{x | myFormat}}
    </li>
</ul>

<script>
var app = angular.module('myApp', []);
app.filter('myFormat', function() {
    return function(x) {
        var i, c, txt = "";
        x = x.split("")
        for (i = 0; i < x.length; i++) {
            c = x[i];
            if (i % 2 == 0) {
                c = c.toUpperCase();
            }
            txt += c;
        }
        return txt;
    };
});
app.controller('namesCtrl', function($scope) {
    $scope.names = ['Jani', 'Carl', 'Margareth', 'Hege', 'Joe', 'Gustav', 'Birgit', 'Mary', 'Kai'];
});
</script>

AngularJS Services


In AngularJS you can make your own service, or use one of the many built-in services.

What is a Service?

In AngularJS, a service is a function, or object, that is available for, and limited to, your AngularJS application.
AngularJS has about 30 built-in services. One of them is the $location service.
The $location service has methods which return information about the location of the current web page:

Example

Use the $location service in a controller:
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $location) {
    $scope.myUrl = $location.absUrl();
});
Note that the $location service is passed in to the controller as an argument. In order to use the service in the controller, it must be defined as a dependency.

Why use Services?

For many services, like the $location service, it seems like you could use objects that are already in the DOM, like the window.location object, and you could, but it would have some limitations, at least for your AngularJS application.
AngularJS constantly supervises your application, and for it to handle changes and events properly, AngularJS prefers that you use the $location service instead of the window.location object.

The $http Service

The $http service is one of the most common used services in AngularJS applications. The service makes a request to the server, and lets your application handle the response.

Example

Use the $http service to request data from the server:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
    $http.get("welcome.htm").then(function (response) {
        $scope.myWelcome = response.data;
    });
});
This example demonstrates a very simple use of the $http service. Learn more about the $http service in the AngularJS Http Tutorial.

The $timeout Service

The $timeout service is AngularJS' version of the window.setTimeout function.

Example

Display a new message after two seconds:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $timeout) {
    $scope.myHeader = "Hello World!";
    $timeout(function () {
        $scope.myHeader = "How are you today?";
    }, 2000);
});

The $interval Service

The $interval service is AngularJS' version of the window.setInterval function.

Example

Display the time every second:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $interval) {
    $scope.theTime = new Date().toLocaleTimeString();
    $interval(function () {
        $scope.theTime = new Date().toLocaleTimeString();
    }, 1000);
});

Create Your Own Service

To create your own service, connect your service to the module:
Create a service named hexafy:
app.service('hexafy', function() {
    this.myFunc = function (x) {
        return x.toString(16);
    }
});
To use your custom made service, add it as a dependency when defining the filter:

Example

Use the custom made service named hexafy to convert a number into a hexadecimal number:
app.controller('myCtrl', function($scope, hexafy) {
    $scope.hex = hexafy.myFunc(255);
});

Use a Custom Service Inside a Filter

Once you have created a service, and connected it to your application, you can use the service in any controller, directive, filter, or even inside other services.
To use the service inside a filter, add it as a dependency when defining the filter:
The service hexafy used in the filter myFormat:
app.filter('myFormat',['hexafy', function(hexafy) {
    return function(x) {
        return hexafy.myFunc(x);
    };
}]);
You can use the filter when displaying values from an object, or an array:
Create a service named hexafy:
<ul>
<li ng-repeat="x in counts">{{x | myFormat}}</li>
</ul> 

AngularJS AJAX - $http


$http is an AngularJS service for reading data from remote servers.

AngularJS $http

The AngularJS $http service makes a request to the server, and returns a response.

Example

Make a simple request to the server, and display the result in a header:
<div ng-app="myApp" ng-controller="myCtrl">

<p>Today's welcome message is:</p>
<h1>{{myWelcome}}</h1>

</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
    $http.get("welcome.htm")
    .then(function(response) {
        $scope.myWelcome = response.data;
    });
});
</script>

Methods

The example above uses the .get method of the $http service.
The .get method is a shortcut method of the $http service. There are several shortcut methods:
  • .delete()
  • .get()
  • .head()
  • .jsonp()
  • .patch()
  • .post()
  • .put()
The methods above are all shortcuts of calling the $http service:

Example

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
    $http({
        method : "GET",
        url : "welcome.htm"
    }).then(function mySucces(response) {
        $scope.myWelcome = response.data;
    }, function myError(response) {
        $scope.myWelcome = response.statusText;
    });
});
The example above executes the $http service with an object as an argument. The object is specifying the HTTP method, the url, what to do on success, and what to do on failure.

Properties

The response from the server is an object with these properties:
  • .config the object used to generate the request.
  • .data a string, or an object, carrying the response from the server.
  • .headers a function to use to get header information.
  • .status a number defining the HTTP status.
  • .statusText a string defining the HTTP status.

Example

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
    $http.get("welcome.htm")
    .then(function(response) {
        $scope.content = response.data;
        $scope.statuscode = response.status;
        $scope.statustext = response.statustext;
    });
});
To handle errors, add one more functions to the .then method:

Example

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
    $http.get("wrongfilename.htm")
    .then(function(response) {
        //First function handles success        $scope.content = response.data;
    }, function(response) {
        //Second function handles error        $scope.content = "Something went wrong";
    });
});

JSON

The data you get from the response is expected to be in JSON format.
JSON is a great way of transporting data, and it is easy to use within AngularJS, or any other JavaScript.
Example: On the server we have a file that returns a JSON object containing 15 customers, all wrapped in array called records.
Take a look at the JSON object.

Example

The ng-repeat directive is perfect for looping through an array:
<div ng-app="myApp" ng-controller="customersCtrl">

<ul>
  <li ng-repeat="x in myData">
    {{ x.Name + ', ' + x.Country }}
  </li>
</ul>

</div>

<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
    $http.get("customers.php").then(function(response) {
        $scope.myData = response.data.records;
    });
});
</script>

AngularJS Tables


The ng-repeat directive is perfect for displaying tables.

Displaying Data in a Table

Displaying tables with angular is very simple:

AngularJS Example

<div ng-app="myApp" ng-controller="customersCtrl">

<table>
  <tr ng-repeat="x in names">
    <td>{{ x.Name }}</td>
    <td>{{ x.Country }}</td>
  </tr>
</table>

</div>

<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
    $http.get("http://www.w3schools.com/angular/customers.php")
    .then(function (response) {$scope.names = response.data.records;});
});
</script>

Displaying with CSS Style

To make it nice, add some CSS to the page:

CSS Style

<style>
table, th , td
{
  border: 1px solid grey;
  border-collapse: collapse;
  padding: 5px;
}
table tr:nth-child(odd) {
  background-color: #f1f1f1;
}
table tr:nth-child(even) {
  background-color: #ffffff;
}
</style>

Display with orderBy Filter

To sort the table, add an orderBy filter: 

AngularJS Example

<table>
  <tr ng-repeat="x in names | orderBy : 'Country'">
    <td>{{ x.Name }}</td>
    <td>{{ x.Country }}</td>
  </tr>
</table>

Display with uppercase Filter

To display uppercase, add an uppercase filter: 

AngularJS Example

<table>
  <tr ng-repeat="x in names">
    <td>{{ x.Name }}</td>
    <td>{{ x.Country | uppercase }}</td>
  </tr>
</table>

Display the Table Index ($index)

To display the table index, add a <td> with $index

AngularJS Example

<table>
  <tr ng-repeat="x in names">
    <td>{{ $index + 1 }}</td>
    <td>{{ x.Name }}</td>
    <td>{{ x.Country }}</td>
  </tr>
</table>

Using $even and $odd

AngularJS Example

<table>
<tr ng-repeat="x in names">
<td ng-if="$odd" style="background-color:#f1f1f1">{{ x.Name }}</td>
<td ng-if="$even">{{ x.Name }}</td>
<td ng-if="$odd" style="background-color:#f1f1f1">{{ x.Country }}</td>
<td ng-if="$even">{{ x.Country }}</td>
</tr>
</table>

AngularJS Select Boxes


AngularJS lets you create dropdown lists based on items in an array, or an object.

Creating a Select Box Using ng-options

If you want to create a dropdown list, based on a object or an array in AngularJS, you should use the ng-option directive:

Example

<div ng-app="myApp" ng-controller="myCtrl">

<select ng-model="selectedName" ng-options="x for x in names">
</select>

</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.names = ["Emil", "Tobias", "Linus"];
});
</script>

ng-options vs ng-repeat

You can also use the ng-repeat directive to make the same dropdown list:

Example

<select>
<option ng-repeat="x in names">{{x}}</option>
</select>
Because the ng-repeat directive repeats a block of HTML code for each item in an array, it can be used to create options in a dropdown list, but the ng-options directive was made especially for filling a dropdown list with options, and has at least one important advantage:
Dropdowns made with ng-options allows the selected value to be an object, while dropdowns made from ng-repeat has to be a string.

What Do I Use?

Assume you have an array of objects:
$scope.cars = [
    {model : "Ford Mustang", color : "red"},
    {model : "Fiat 500", color : "white"},
    {model : "Volvo XC90", color : "black"}
];
The ng-repeat directive has it's limitations, the selected value must be a string:

Example

Using ng-repeat:
<select ng-model="selectedCar">
<option ng-repeat="x in cars" value="{{x.model}}">{{x.model}}</option>
</select>

<h1>You selected: {{selectedCar}}</h1>
When using the ng-options directive, the selected value can be an object:

Example

Using ng-options:
<select ng-model="selectedCar" ng-options="x.model for x in cars">
</select>

<h1>You selected: {{selectedCar.model}}</h1>
<p>It's color is: {{selectedCar.color}}</p>
When the selected value can be an object, it can hold more information, and your application can be more flexible.
We will use the ng-options directive in this tutorial.

The Data Source as an Object

In the previous examples the data source was an array, but we can also use an object.
Assume you have an object with key-value pairs:
$scope.cars = {
    car01 : "Ford",
    car02 : "Fiat",
    car03 : "Volvo"
};
The expression in the ng-options attribute is a bit different for objects:

Example

Using an object as the data source, x represents the key, and y represents the value:
<select ng-model="selectedCar" ng-options="x for (x, y) in cars">
</select>

<h1>You selected: {{selectedCar}}</h1>
The selected value will always be the value in a key-value pair.
The value in a key-value pair can also be an object:

Example

The selected value will still be the value in a key-value pair, only this time it is an object:
$scope.cars = {
car01 : {brand : "Ford", model : "Mustang", color : "red"},
car02 : {brand : "Fiat", model : "500", color : "white"},
car03 : {brand : "Volvo", model : "XC90", color : "black"}
};
The options in the dropdown list does not have be the key in a key-value pair, it can also be the value, or a property of the value object:

Example

<select ng-model="selectedCar" ng-options="y.brand for (x, y) in cars">
</select> 

AngularJS SQL


AngularJS is perfect for displaying data from a Database. Just make sure the data is in JSON format.

Fetching Data From a PHP Server Running MySQL

AngularJS Example

<div ng-app="myApp" ng-controller="customersCtrl">

<table>
  <tr ng-repeat="x in names">
    <td>{{ x.Name }}</td>
    <td>{{ x.Country }}</td>
  </tr>
</table>

</div>

<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
    $http.get("http://www.w3schools.com/angular/customers_mysql.php")
    .then(function (response) {$scope.names = response.data.records;});
});
</script>

Fetching Data From an ASP.NET Server Running SQL

AngularJS Example

<div ng-app="myApp" ng-controller="customersCtrl">

<table>
  <tr ng-repeat="x in names">
    <td>{{ x.Name }}</td>
    <td>{{ x.Country }}</td>
  </tr>
</table>

</div>

<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
    $http.get("http://www.w3schools.com/angular/customers_sql.aspx")
    .then(function (response) {$scope.names = response.data.records;});
});
</script>

Server Code Examples

The following section is a listing of the server code used to fetch SQL data.
  1. Using PHP and MySQL. Returning JSON.
  2. Using PHP and MS Access. Returning JSON.
  3. Using ASP.NET, VB, and MS Access. Returning JSON.
  4. Using ASP.NET, Razor, and SQL Lite. Returning JSON.

Cross-Site HTTP Requests

Requests for data from a different server (than the requesting page), are called cross-site HTTP requests.
Cross-site requests are common on the web. Many pages load CSS, images, and scripts from different servers.
In modern browsers, cross-site HTTP requests from scripts are restricted to same site for security reasons.
The following line, in our PHP examples, has been added to allow cross-site access.
header("Access-Control-Allow-Origin: *");

1. Server Code PHP and MySQL

<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

$conn = new mysqli("myServer", "myUser", "myPassword", "Northwind");

$result = $conn->query("SELECT CompanyName, City, Country FROM Customers");

$outp = "";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
    if ($outp != "") {$outp .= ",";}
    $outp .= '{"Name":"'  . $rs["CompanyName"] . '",';
    $outp .= '"City":"'   . $rs["City"]        . '",';
    $outp .= '"Country":"'. $rs["Country"]     . '"}';
}
$outp ='{"records":['.$outp.']}';
$conn->close();

echo($outp);
?>

2. Server Code PHP and MS Access

<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=ISO-8859-1");

$conn = new COM("ADODB.Connection");
$conn->open("PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=Northwind.mdb");

$rs = $conn->execute("SELECT CompanyName, City, Country FROM Customers");

$outp = "";
while (!$rs->EOF) {
    if ($outp != "") {$outp .= ",";}
    $outp .= '{"Name":"'  . $rs["CompanyName"] . '",';
    $outp .= '"City":"'   . $rs["City"]        . '",';
    $outp .= '"Country":"'. $rs["Country"]     . '"}';
    $rs->MoveNext();
}
$outp ='{"records":['.$outp.']}';

$conn->close();

echo ($outp);
?>

3. Server Code ASP.NET, VB and MS Access

<%@ Import Namespace="System.IO"%>
<%@ Import Namespace="System.Data"%>
<%@ Import Namespace="System.Data.OleDb"%>
<%
Response.AppendHeader("Access-Control-Allow-Origin", "*")
Response.AppendHeader("Content-type", "application/json")
Dim conn As OleDbConnection
Dim objAdapter As OleDbDataAdapter
Dim objTable As DataTable
Dim objRow As DataRow
Dim objDataSet As New DataSet()
Dim outp
Dim c
conn = New OledbConnection("Provider=Microsoft.Jet.OLEDB.4.0;data source=Northwind.mdb")
objAdapter = New OledbDataAdapter("SELECT CompanyName, City, Country FROM Customers", conn)
objAdapter.Fill(objDataSet, "myTable")
objTable=objDataSet.Tables("myTable")

outp = ""
c = chr(34)
for each x in objTable.Rows
if outp <> "" then outp = outp & ","
outp = outp & "{" & c & "Name"    & c & ":" & c & x("CompanyName") & c & ","
outp = outp &       c & "City"    & c & ":" & c & x("City")        & c & ","
outp = outp &       c & "Country" & c & ":" & c & x("Country")     & c & "}"
next

outp ="{" & c & "records" & c & ":[" & outp & "]}"
response.write(outp)
conn.close
%>

4. Server Code ASP.NET, Razor C# and SQL Lite

@{
Response.AppendHeader("Access-Control-Allow-Origin", "*")
Response.AppendHeader("Content-type", "application/json")
var db = Database.Open("Northwind");
var query = db.Query("SELECT CompanyName, City, Country FROM Customers");
var outp =""
var c = chr(34)
}
@foreach(var row in query)
{
if outp <> "" then outp = outp + ","
outp = outp + "{" + c + "Name"    + c + ":" + c + @row.CompanyName + c + ","
outp = outp +       c + "City"    + c + ":" + c + @row.City        + c + ","
outp = outp +       c + "Country" + c + ":" + c + @row.Country     + c + "}"
}
outp ="{" + c + "records" + c + ":[" + outp + "]}"
@outp

AngularJS HTML DOM


AngularJS has directives for binding application data to the attributes of HTML DOM elements.

The ng-disabled Directive

The ng-disabled directive binds AngularJS application data to the disabled attribute of HTML elements.

AngularJS Example

<div ng-app="" ng-init="mySwitch=true">

<p>
<button ng-disabled="mySwitch">Click Me!</button>
</p>

<p>
<input type="checkbox" ng-model="mySwitch">Button
</p>

<p>
{{ mySwitch }}
</p>

</div>
Application explained:
The ng-disabled directive binds the application data mySwitch to the HTML button's disabled attribute.
The ng-model directive binds the value of the HTML checkbox element to the value of mySwitch.
If the value of mySwitch evaluates to true, the button will be disabled: 
<p>
<button disabled>Click Me!</button>
</p>
If the value of mySwitch evaluates to false, the button will not be disabled: 
<p>
<button>Click Me!</button>
</p>

The ng-show Directive

The ng-show directive shows or hides an HTML element.

AngularJS Example

<div ng-app="">

<p ng-show="true">I am visible.</p>

<p ng-show="false">I am not visible.</p>

</div>
The ng-show directive shows (or hides) an HTML element based on the value of ng-show.
You can use any expression that evaluates to true or false:

AngularJS Example

<div ng-app="" ng-init="hour=13">

<p ng-show="hour > 12">I am visible.</p>

</div>
Note In the next chapter, there are more examples, using the click of a button to hide HTML elements.

The ng-hide Directive

The ng-hide directive hides or shows an HTML element.

AngularJS Example

<div ng-app="">

<p ng-hide="true">I am not visible.</p>

<p ng-hide="false">I am visible.</p>

</div>

AngularJS Events


AngularJS has its own HTML events directives.

AngularJS Events

You can add AngularJS event listeners to your HTML elements by using one or more of these directives:
  • ng-blur
  • ng-change
  • ng-click
  • ng-copy
  • ng-cut
  • ng-dblclick
  • ng-focus
  • ng-keydown
  • ng-keypress
  • ng-keyup
  • ng-mousedown
  • ng-mouseenter
  • ng-mouseleave
  • ng-mousemove
  • ng-mouseover
  • ng-mouseup
  • ng-paste
The event directives allows us to run AngularJS functions at certain user events.
An AngularJS event will not overwrite an HTML event, both events will be executed.

Mouse Events

Mouse events occur when the cursor moves over an element, in this order:
  1. ng-mouseenter
  2. ng-mouseover
  3. ng-mousemove
  4. ng-mouseleave
Or when a mouse button is clicked on an element, in this order:
  1. ng-mousedown
  2. ng-mouseup
  3. ng-click
You can add mouse events on any HTML element.

Example

Increase the count variable when the mouse moves over the H1 element:
<div ng-app="myApp" ng-controller="myCtrl">

<h1 ng-mousemove="count = count + 1">Mouse over me!</h1>

<h2>{{ count }}</h2>

</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.count = 0;
});
</script>

The ng-click Directive

The ng-click directive defines AngularJS code that will be executed when the element is being clicked.

Example

<div ng-app="myApp" ng-controller="myCtrl">

<button ng-click="count = count + 1">Click me!</button>

<p>{{ count }}</p>

</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.count = 0;
});
</script>

You can also refer to a function:

Example

<div ng-app="myApp" ng-controller="myCtrl">

<button ng-click="myFunction()">Click me!</button>

<p>{{ count }}</p>

</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.count = 0;
    $scope.myFunction = function() {
        $scope.count++;
    }
});
</script>

Toggle, True/False

If you want to show a section of HTML code when a button is clicked, and hide when the button is clicked again, like a dropdown menu, make the button behave like a toggle switch:

Example

<div ng-app="myApp" ng-controller="myCtrl">

<button ng-click="myFunc()">Click Me!</button>

<div ng-show="showMe">
    <h1>Menu:</h1>
    <div>Pizza</div>
    <div>Pasta</div>
    <div>Pesce</div>
</div>

</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.showMe = false;
    $scope.myFunc = function() {
        $scope.showMe = !$scope.showMe;
    }
});
</script>
The showMe variable starts out as the Boolean value false.
The myFunc function sets the showMe variable to the opposite of what it is, by using the ! (not) operator.

$event Object

You can pass the $event object as an argument when calling the function.
The $event object contains the browser's event object:

Example

<div ng-app="myApp" ng-controller="myCtrl">

<h1 ng-mousemove="myFunc($event)">Mouse Over Me!</h1>

<p>Coordinates: {{x + ', ' + y}}</p>

</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.myFunc = function(myE) {
        $scope.x = myE.clientX;
        $scope.y = myE.clientY;
    }
});
</script>

AngularJS Forms


Forms in AngularJS provides data-binding and validation of input controls.

Input Controls

Input controls are the HTML input elements:
  • input elements
  • select elements
  • button elements
  • textarea elements

Data-Binding

Input controls provides data-binding by using the ng-model directive.
<input type="text" ng-model="firstname">
The application does now have a property named firstname.
The ng-model directive binds the input controller to the rest of your application.
The property firstname, can be referred to in a controller:

Example

<script>
var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
    $scope.firstname = "John";
});
</script>
It can also be referred to elsewhere in the application:

Example

<form>
First Name: <input type="text" ng-model="firstname">
</form>

<h1>You entered: {{firstname}}</h1>

Checkbox

A checkbox has the value true or false. Apply the ng-model directive to a checkbox, and use it's value in your application.

Example

Show the header if the checkbox is checked:
 <form>
    Check to show a header:
    <input type="checkbox" ng-model="myVar">
</form>

<h1 ng-show="myVar">My Header</h1>

Radiobuttons

Bind radio buttons to your application with the ng-model directive.
Radio buttons with the same ng-model can have different values, but only the selected one will be used.

Example

Display some text, based on the value of the selected radio button:
 <form>
Pick a topic:
<input type="radio" ng-model="myVar" value="dogs">Dogs
<input type="radio" ng-model="myVar" value="tuts">Tutorials
<input type="radio" ng-model="myVar" value="cars">Cars
</form>
The value of myVar will be either dogs, tuts, or cars.

Selectbox

Bind select boxes to your application with the ng-model directive.
The property defined in the ng-model attribute will have the value of the selected option in the selectbox.

 Example

Display some text, based on the value of the selected option:
<form>
Select a topic:
<select ng-model="myVar">
    <option value="">
    <option value="dogs">Dogs
    <option value="tuts">Tutorials
    <option value="cars">Cars
</select>
</form>
The value of myVar will be either dogs, tuts, or cars.

An AngularJS Form Example

First Name:

Last Name:


form = {"firstName":"John","lastName":"Doe"}
master = {"firstName":"John","lastName":"Doe"}

Application Code

<div ng-app="myApp" ng-controller="formCtrl">
  <form novalidate>
    First Name:<br>
    <input type="text" ng-model="user.firstName"><br>
    Last Name:<br>
    <input type="text" ng-model="user.lastName">
    <br><br>
    <button ng-click="reset()">RESET</button>
  </form>
  <p>form = {{user}}</p>
  <p>master = {{master}}</p>
</div>

<script>
var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
    $scope.master = {firstName: "John", lastName: "Doe"};
    $scope.reset = function() {
        $scope.user = angular.copy($scope.master);
    };
    $scope.reset();
});
</script>
Note The novalidate attribute is new in HTML5. It disables any default browser validation.

Example Explained

The ng-app directive defines the AngularJS application.
The ng-controller directive defines the application controller.
The ng-model directive binds two input elements to the user object in the model.
The formCtrl controller sets initial values to the master object, and defines the reset() method.
The reset() method sets the user object equal to the master object.
The ng-click directive invokes the reset() method, only if the button is clicked.
The novalidate attribute is not needed for this application, but normally you will use it in AngularJS forms, to override standard HTML5 validation.