Tutorial for Two Way Data Binding Using AngularJS
💻 coding

Tutorial for Two Way Data Binding Using AngularJS

3 min read 603 words
3 min read
ShareWhatsAppPost on X
  • 1Two-way data binding in AngularJS synchronizes the model and view, updating one when the other changes.
  • 2The tutorial provides a sample database structure for storing comments, including fields for comment ID, text, and timestamp.
  • 3Key AngularJS directives used include ng-app, ng-controller, ng-model, ng-repeat, and ng-click for dynamic data handling.

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"Two-way data binding in AngularJS synchronizes the model and view, updating one when the other changes."

Tutorial for Two Way Data Binding Using AngularJS

This post is the continuation of my previous AngularJS tutorial, I had explained JSON parsing using AngularJS. In this, we are going to explain how to do two-way data binding with Angular JS. Data binding is the most useful feature in AngularJS, It will help you to save from writing a lot of regular code.

What is two-way data binding

Angular template engine binding the data in two way, which means it synchronizes the data between model and view, its update the view component when the model get change and vice versa.

Sample Database

Sample database comments table contains four comment id, comments and timestamp.

CREATE TABLE IF NOT EXISTS `comments` (
`comment_id` int(9) NOT NULL AUTO_INCREMENT,
`comments` text NOT NULL,
`timestamp` int(11) NOT NULL,
PRIMARY KEY (`comment_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;

Javascript

A global header for all ajax request charset should be utf-8 and form data should be encoded.

<script src="js/angular.min.js"></script>
<script>
function commentsController($scope, $http)
{

$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
$http.get("index.php?action=getComments").success(function(data)
{
$scope.comments = data;
 });

$scope.addComment = function(comment){
// Validate the comment is not an empty and undefined
if("undefined" != comment.msg){
// Angular AJAX call
$http({
method : "POST",
url : "index.php", 
data : "action=add&msg="+comment.msg
}).success(function(data){
// Add the data into DOM for future use
$scope.comments.unshift(data); 
});
$scope.comment = "";
}
}

// index : index of global DOM
$scope.deleteComment = function(index){
// Angular AJAX call
$http({
method : "GET",
url : "index.php?action=delete&id="+$scope.comments[index].id,
}).success(function(data){
// Removing Data from Global DOM
$scope.comments.splice(index,1);
});
}
}
</script>

ng-app

It will load the dependencies and the module.

ng-controller

Used to call the controller

ng-model

Initiate Two Way binding

ng-repeat

Angular control structure act as for loop

ng-click

Angular on click event

HTML Code

<div ng-app id="ng-app" class="main">
<div ng-controller="commentsController">

<!-- Update Box -->
<textarea name="submitComment" ng-model="comment.msg" placeholder="What are you thinking?"></textarea>
<a href="javascript:void(0);" class="button" ng-click="addComment(comment)">POST</a>

<!-- Comments -->
<div ng-repeat="comment in comments">
<div class="updates">
<a href="javascript:void(0);" ng-click="deleteComment($index);">Delete</a>
{{comment.msg}}
</div>
</div>

</div>
</div>

index.php

<?php
require_once("comments.php");
$comment = new comments();

// Get all the comments while loading the page
if(isset($_GET['action']) and $_GET['action'] == "getComments"){
echo $comment->getComments();
exit;
}

// Handle Delete AJAX Call
if(isset($_GET['action']) and $_GET['action'] == "delete"){
$comment->deleteComment($_GET['id']);
exit;
}

// Handle Add AJAX Call
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
echo $comment->addComment($_POST);
exit;
}

?>

comments.php

Contains PHP code here just modify database access credentials.

<?php
class db {

const SERVER = "localhost";
const USER = "username";
const PASSWORD = "password";
const DB = "database_name";

private static $instance = NULL;
private $connection;

private function __construct(){
$this->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
}

// Secure way to create Database Connection through SINGLETON Model
protected static function dbInstance(){
if(NULL == self::$instance){
self::$instance = new self;
}
return self::$instance;
}
}

class comments extends db {

var $con;

public function __construct(){
parent::dbInstance();
}

public function getComments(){
$qry = mysql_query("SELECT comment_id, comments, timestamp FROM comments ORDER BY timestamp DESC");
$data = array();
while($rows = mysql_fetch_array($qry)){
$data[] = array("id" => $rows['comment_id'],
"msg" => $rows['comments'],
"timestamp" => $rows['timestamp']);
}
return json_encode($data);
}

public function addComment($post){
$comments = mysql_escape_string($post['msg']);
$time = time();
$id = 0;
$qry = mysql_query("INSERT INTO comments(comments,timestamp)VALUES('{$comments}','{$time}')")or die(mysql_error());
$id = mysql_insert_id();
return json_encode(array("id" => $id,
"msg" => stripslashes($comments),
"timestamp" => $time));
}

public function deleteComment($id){
(int)$id = mysql_escape_string($id);
$del = mysql_query("DELETE FROM comments WHERE comment_id = ".$id);
if($del)
return true;
return false;
}

}
?>

CSS

* { padding:0px; margin:0px; }
body{font-family:arial}
textarea{border:solid 1px #333;width:520px;height:30px;font-family:arial;padding:5px}
.main{margin:0 auto;width:600px; text-align:left:}
.updates
{
padding:20px 10px 20px 10px ;
border-bottom:dashed 1px #999;
background-color:#f2f2f2;
}
.button
{
padding:10px;
float:right;
background-color:#006699;
color:#fff;
font-weight:bold;
text-decoration:none;
}
.updates a
{
color:#cc0000;
font-size:12px;
}

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

AskGif

Published on 30 August 2019 · 3 min read · 603 words

Part of AskGif Blog · coding

You might also like

Tutorial for Two Way Data Binding Using AngularJS | AskGif Blog