AngularJS Tutorial Two Way Data Binding
Wall Script
Wall Script
Monday, September 16, 2013

AngularJS Tutorial Two Way Data Binding

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 lots of regular code.

AngularJS Tutorial.


Download Script     Live Demo

Author
Arun Kumar Sekar
Arun Kumar Sekar

Engineer, Plugin Expert
Chennai, INDIA

What is two way data binding
Angular template engine binding the data in two way, which means it synchronize 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;
}

?>

//HTML Code

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;
}
web notification

33 comments:

  1. Nice Tutorial. We need more tutorials on AngularJS.

    ReplyDelete
  2. It's good. Indentation to the code is required.
    :)

    ReplyDelete
  3. thank you very much.

    ReplyDelete
  4. I visit your website first time, but really i impressed a lot. No doubt that you are a good and successful blogger. Your all post are good, but i check few of them, which i prefer best.

    Your article is very information, I read your article completely. Thanks for sharing.

    ReplyDelete
  5. Awesome article.. keep up the goof work

    ReplyDelete
  6. very good post for beginners...was looking for a angular beginner tutorial like this one...thanks very much...

    ReplyDelete
  7. good tutorial but i have some problems with Db thing if you realy saving those data in database why cant we see the data after we refresh the page??

    ReplyDelete
  8. great job, thanks !

    ReplyDelete
  9. Great illustration. Good set of example. I loved reading your post. Bookmarking it right away.
    Btw I am a fan of Angular JS. I wrote on How databinding works in Angular JS? . I would love to get feedback from you on this.

    ReplyDelete
  10. I retain listening to distinct news speak about getting free online grant applications so I have been looking around for genuine greatest AUTO

    ReplyDelete
  11. Can you tell me how to retrieve data from database and store it in Json file. in angularjs. i am not using pHP, i'm using Angularjs and JS.

    ReplyDelete
  12. ng-model="comment.msg"

    ReplyDelete
  13. Excellent article on Angular Two Way Bindings

    ReplyDelete
  14. where i have to placde the script

    ReplyDelete
  15. Can I download your stuff from github?

    ReplyDelete
  16. Unless I'm missing something, this is not actually two-way binding because if the database updates, the front end doesn't, until you hit Reload. Surely two-way would mean we could add data to the DB and see the DOM update independently?

    ReplyDelete

mailxengine Youtueb channel
Make in India
X