Two way data binding in angularjs framework is approach to synchronize the data between model and view. What it means that if there is any change happens in model ( Back-end ) then view ( front-end ) will be updated and vice versa.
You can use this approach to build high performance web application with less efforts. To do the same binding in jQuery you need to write a logic in both of the layer i.e model and view but in angularjs you just have to bind the variable using $scope and angular handle the rest.
Our Application : News Feed
To demonstrate the example and power of two way data binding in angularjs we are going to build one simple news feed web app which contains profile pictures and status updates (static just for demo purpose).
We store the profile picture URL in MySQL back-end. At front-end we will bind the variable which stores profile picture URL with $scope and as soon as profile picture updates in model view i.e news feed profile picture should be updated.
We are going to use Node as back-end which handle the operation with MySQL. Data will be passed using JSON format.
Project Architecture.
Front-end will call API using $http variable to Node Server. Node server will deal with MySQL database and fetch the live feeds. After fetching it will pack it in JSON and send the response back to front-end.
We will use $interval angular directive to poll the model in specified time. When $scope changes it will be updated to view (front-end).
Our Database:
Like i have mentioned we are going to MySQL as backend. Create any database using phpmyadmin and create table inside it as ‘user_info‘.
Create two rows with the proper name as shown below.
Once done. Go to SQL tab and insert some demo rows. Here are some which i used while developing the app.
('http://www.canvas101.co.uk/images/gallery-art/Famous%20&%20Iconic/Movies/MO0549%20batman%20logo.jpg');
INSERT INTO `user_info`(`profile_picture`) VALUES
('http://www.mrwallpaper.com/wallpapers/Joker-Batman-Art-1920x1200.jpg');
INSERT INTO `user_info`(`profile_picture`) VALUES ('http://img1.wikia.nocookie.net/__cb20120511112335/batman/images/f/f0/Bane_TDKR3.jpg');
Our Node Server :
We are going to use express and mysql node packages. Here is our package.json file.
"name": "two-way-data-binding",
"version": "1.0.0",
"dependencies": {
"express": "~4.9.2",
"mysql": "~2.5.0"
}
}
Install dependencies using
We have to first require the important file in our Server.js and then define the MySQL parameters and express router. Here is a code of Node Server.
var mysql = require("mysql");
var app = express();
/*
* Configure MySQL parameters.
*/
var connection = mysql.createConnection({
host : "localhost",
user : "root",
password : "",
database : "two_way_demo"
});
/*Connecting to Database*/
connection.connect(function(error){
if(error)
{
console.log("Problem with MySQL"+error);
}
else
{
console.log("Connected with Database");
}
});
/*Start the Server*/
app.listen(3000,function(){
console.log("It's Started on PORT 3000");
});
At this point of time we have Node server ready to accept request but it don’t know what it have to do with those requests. We are going to use two router requests.
Router | Action |
---|---|
/ | Return home page |
/load | Return news feed from database |
Here is our router code.
res.sendfile('index.html');
});
/*
* Here we will call Database.
* Fetch news from table.
* Return it in JSON.
*/
app.get('/load',function(req,res){
connection.query("SELECT * from user_info",function(err,rows){
if(err)
{
console.log("Problem with MySQL"+err);
}
else
{
res.end(JSON.stringify(rows));
}
});
});
Testing Server and Router
Before moving ahead with view (angular part) let’s first test whether our API calls are working or not. Start the Server using
I use postman chrome extension to simulate the API calls. Here is what i got after calling /load API.
We are getting the JSON response means our API is working. Let’s code our view and bind the profile pictures to $scope.
Angular and two way binding:
Here is a angular app and controller code.
here is controller code.
load_pictures();
$interval(function(){
load_pictures();
},300);
function load_pictures(){
$http.get('http://localhost:3000/load').success(function(data){
$scope.profile_pictures=data;
});
};
});
i have made one function called load_pictures() which calls the API we have tested above. It assigns the return data to $scope.profile_pictures. This is two way data binding in angularjs.
We use $interval angular directive to call server in specific time interval.
In our HTML code. We have added the angular js library with our js file in script tag. Then we are ng-repeat to print the binded data to the HTML. Here is a code.
<head>
<title>Two way Data binding Demo</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script src="angular.js"></script>
<script src="app.js"></script>
<script src="core.js"></script>
</head>
<body>
<div id="container" ng-app='two_way' ng-controller='two_way_control'>
<div class="row" ng-repeat="data in profile_pictures">
<div class=".col-sm-6 .col-md-5 .col-lg-6" style="background-color:#eee;height:150px;width:500px;margin-left:240px;margin-top:20px;">
<h4 style="padding:10px;">User Say's</h4><hr>
<p style="padding:10px;">
This is a Demo feed. It is developed to demonstrate Two way data binding.
</p>
<img src="{{data.profile_picture}}" class="img-circle" style="width:100px;height:100px;margin-left:-140px;margin-top:-130px;">
</div>
</div>
</div>
</body>
</html>
Notice the line “data in profile_pictures”. This is the $scope.profile_pictures. By using ng-repeat we have traversed through number of data in that variable and printing it as image.
Now as soon as we change something in Model. View will reflect the same change. You can view demo of this app at youtube.