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:

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:

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

ng-model:

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

ng-repeat:

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

ng-click:

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` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(200) DEFAULT NULL,
`amount` varchar(200) DEFAULT NULL,
`date` date DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=latin1;

/*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

<?php

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);

if($this->connection){
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(){
parent::dbInstance();
}

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);
if($del)
return true;
return false;
}

}
?>

3. Create our app view

<?php

require_once("expenses.php");

$expenses = new expenses();

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

echo $expenses-&gt;getExpenses();

exit;
}

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

if(isset($_GET['action']) and $_GET['action'] == "delete"){
$expenses-&gt;deleteExpense($_GET['id']);
exit;
}
?>

<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>
</nav>
<div class="container">
<div><!-- Add an Expenses --></div>
</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>
</div>
</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">{{expense.date}} {{expense.name}}</span>
Rs {{expense.amount}}
<button class="btn btn-danger pull-right btn-s" type="button"> </button></li>
</ul>
</div>
</div>
<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){
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
$http.get("index.php?action=getExpenses")
.success(function(data){ $scope.expenses = data; });

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

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

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