Two Way Data Binding In AngularJS with Directives

Abhigyan Singh 12th Jul 2020

In this post I am going to explain two way data binding in AngularJs, two way data binding means data is being synced between model to view and view to model in realtime, which means view gets updated as soon as model get change and vice versa.

It means that any data which change in model will directly change into its respective view. Two way data binding in angular js is a responsive feature to show immediate response of user’s action. Here we just need to declare two way to data winding relationship by a directive.

In the example I have used following directives of angularjs : ng-app, ng-controller, ng-model, ng-repeat, ng-click


ng-app directives is used to show the root element of angular js. All angular js application must have only have ng-app directive.


ng-controller directive is used to define angular js controller.


ng-model directive is used to bind the value of input field to a vairaible.


ng-repeat directive is used to repeat the set of html.


It tells that when a element or button is clicked.

Code explanation of two way data binding in AngularJs

1.  First of all we will create a database and table for our app

/*Table structure for table `myexpenses` */

DROP TABLE IF EXISTS `myexpenses`;

CREATE TABLE `myexpenses` (
`name` varchar(200) DEFAULT NULL,
`amount` varchar(200) DEFAULT NULL,
`date` date DEFAULT NULL,

/*Data for the table `myexpenses` */

insert into `myexpenses`(`id`,`name`,`amount`,`date`) values (6,'Bought Iphone','40000','2016-03-25'),(7,'Bought Laptop','100000','2016-05-04');

2. Make a class file to do CRUD operation in database


class db {

const SERVER = "localhost";

const USER = "root";

const PASSWORD = "";

const DB = "test";

private static $instance = NULL;

private $connection;

private function __construct(){

$this-&gt;connection = mysql_connect(self::SERVER, self::USER, self::PASSWORD);

mysql_select_db(self::DB, $this->connection);

private function __clone(){
// to avoid cloning this class

protected static function dbInstance(){
if(NULL == self::$instance){
self::$instance = new self;
return self::$instance;

class expenses extends db {

var $con;

public function __construct(){

public function getExpenses(){
$qry = mysql_query("SELECT id, name, amount, date FROM myexpenses ORDER BY date DESC");
$data = array();
while($rows = mysql_fetch_array($qry)){
$data[] = array("id" => $rows['id'],
"name" => $rows['name'],
"amount" => $rows['amount'],
"date" => $rows['date']);
return json_encode($data);

public function addExpenses($post){
$name = mysql_escape_string($post['name']);
$date = mysql_escape_string($post['date']);
$amount = mysql_escape_string($post['amount']);
$qry = mysql_query("INSERT INTO myexpenses(name,amount,date)VALUES('{$name}','{$amount}','{$date}')")or die(mysql_error());
$id = mysql_insert_id();
return json_encode(array("id" => $id,
"name" => stripslashes($name),
"amount" => stripslashes($amount),
"date" => $date));

public function deleteExpense($id){
(int)$id = mysql_escape_string($id);
$del = mysql_query("DELETE FROM myexpenses WHERE id = ".$id);
return true;
return false;


3. Create our app view



$expenses = new expenses();

if(isset($_GET['action']) and $_GET['action'] == "getExpenses"){

echo $expenses-&gt;getExpenses();


if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
echo $expenses-&gt;addExpenses($_POST);

if(isset($_GET['action']) and $_GET['action'] == "delete"){

<nav class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header"><span class="navbar-brand"><img class="brand" src="img/logo.png" height="20" /> Expenses Tracker (Two Way Data Binding Demo)</span></div>
<div class="container">
<div><!-- Add an Expenses --></div>
<div class="row">
<div class="col-xs-12">
<div class="alert alert-warning">Please enter valid values in all required fields</div>
<div class="form-group"><input class="form-control" name="submitExpenseName" required="" type="text" placeholder="Expense Description" /></div>
<div class="form-group"><input class="form-control" name="submitExpenseAmount" required="" type="number" placeholder="Amount Spend" /></div>
<div class="form-group"><input class="form-control" name="submitExpenseDate" required="" type="date" /></div>
<div class="form-group"><button class="btn btn-success btn-lg btn-block" type="button"> Add</button></div>
<!-- List of Expenses -->
<div class="row">
<div class="col-xs-12">
<ul class="list-group">
<li class="list-group-item text-center"><span class="col-xs-8 pull-left text-left">{{}} {{}}</span>
Rs {{expense.amount}}
<button class="btn btn-danger pull-right btn-s" type="button"> </button></li>
<script src="js/jquery-1.11.0.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/angular.min.js"></script>
<script src="js/app.js"></script>

4. Write angularjs functionality to manage two way data binding

function expensesController($scope, $http){
$['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
.success(function(data){ $scope.expenses = data; });

$scope.addExpense = function(expense){
if("undefined" !={
method : "POST",
url : "index.php",
data : "action=add&amp;name=""&amp;amount="+expense.amount+"&amp;date="
$scope.expense = "";

$scope.deleteExpense = function(index){
method : "GET",
url : "index.php?action=delete&amp;id="+$scope.expenses[index].id,

Now we have explained the code of two way data binding in AngularJs. You can view demo or download the code. If you have any query, please write us on comment section.

Authored By Abhigyan Singh

He is a continuous blogger and has blogged on different topic. He loves to surf Internet and always trying to get new Idea about new Technology and Innovations and sharing these great information to all the technology lovers.

Also on DiscussDesk