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.
Hello
Actually, you made here a one-way data-binding, no ?
You only update the view with the model, and never the model from the view …
What you have here is nice, but it’s not two-way, IMHO 馃檪
Cheers
Hey i have made that in demo part but i mentioned this in article. It won’t require much time to do if you get a kick start from the project source code. Cheers !
It would be really helpful if you could include the file names you’ve put the code in.
Yes Atbean, i am going to implement this ASAP.
Hi Atbean, i have updated the code with file name. hope it helps.
useful tutorial
What if i need to recover more than one value
what the best way to do that
Hi sassin,
I do not understand your question. Please elaborate.
Thanks.
There is a problem when you typing the url : ‘localhost:3000/load’
it displays all informations in database
It is because in /load router, SQL Query is to Select all data from database. It’s API, you don’t need to hit it via browser.
It’s really nice… 馃檪
Really nice tutorial !! Thanks
Thanks Rishabh.
Hai shahid I am new to nodejs
I need your help can…
This is my mail id
Patibandlaraja176@gmail.com
If possible? I wan talk to you once..
Thanks
Sure.
Shoot me at shahid@codeforgeek.com.
It’s really helpful for beginners… 馃檪
Hey ,
While serving the static content node is asking for js files to serve
as localhost:3000/angular/angular.js
There is a 404 issue regarding this.
Help me solve the problem.
add this line in Server.js file.
app.use(express.static(__dirname + ‘/public’)); //put folder name where angular.js is.
Hi,
I’m getting a MySQL error: connect ECONNREFUSED.
I’m setting up the MySql database on phpMyAdmin through Mamp.
What would you suggest for Mac users?
Thanks.
Hi Nico,
if you are using mamp please make sure MySQL runs on default port ( 3306 ) else define port in code.
hi Nico,
in Server.js make sure you make full changes such as :
“var connection = mysql.createConnection({
host : “localhost”,
user : “root”,
password : “”,
// database : “two_way_demo”
database : “phpmyadmin”
});”
database and password settings, if you have set the root user password on your msql database server.
hello author.
if am not using ng-repeat, how can i make the binding?
Binding will be using $scope only. i used ng-repeat to loop over array of data.
Hey I followed your code but the images don’t load.
It looks like this – http://imgur.com/7nRNV8c
any help please ?
I worked on it and I am now getting this – http://imgur.com/0dG8JVx
the console says –
GET localhost:3000/%7B%7Bdata.profile_pictures%7D%7D 404 (Not Found) localhost/:22
GET localhost:3000/%7B%7Bdata.profile_pictures%7D%7D 404 (Not Found) localhost/:1
I think you are trying to access local images. Please find out some image from Google and paste its link in PHPMyadmin. And if you want to access local images you need to put it in your server file location and also add some little code in Server.js.
I am taking the image from google just like you did in your demo video.
That should work.
I am sincerely thankful for this code.
Is it normal for the app to continuously load? Even after the page and images are loaded?
When I open the Console in Chrome (ctrl+shift+i) it shows line 76 of “angular.js” trying to reload an item of 590 bytes, which is the same size as angular.js itself. Surely that eats a LOT of bandwidth?
ANy idea why it happens, or how to stop it?
function load_pictures(){
$http.get(‘http://localhost:3306/load’).success(function(data){
$scope.profile_pictures=data;
});
hi i have change the port number 3306 is my mysql port when i run this code getting error
oss-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at localhost:3306/load. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
Why are you changing http port to 3306. You should put it the Port on which Node program is running. In my case its 3000.
I have the same error and I use the port 3000.
Did you find a solution ?
Great simple tutorial. The image doesn’t load but I am connected to database.
Very nice tutorial
This is an extremely helpful tutorial. I did run into a problem though. I am able to access the database and create a JSON object, but not able to display it on the page, and also the ng-repeat code doesn’t seem to work for me. Help with this would be much appreciated. I have posted some screenshots showing my output/code.
http://imgur.com/ECyKjhp&HZ6UBuS&rr0eA9o&ULpoj61#3
I have used a service to get the data which json and my data should be auto update as soon as I made changes in json file. I have used the following code
app.factory(’emails’, [‘$http’, ‘$interval’, function ($http, $interval) {
loadData();
$interval(function () {
loadData();
}, 300);
function loadData() {
return $http.get(‘http://118.139.164.199:8082/data/emails.json’)
.success(function (data) {
return data;
})
.error(function (err) {
return err;
});
};
} ]);
can pls look at it and update me whats changes do I need to do as its gives me an error as(http://errors.angularjs.org/1.3.15/$injector/undef?p0=emails).
What is the angular version you are using ?
my version is 1.3.15, so $interval depends on version…?
It should work on 1.3.15. Let me have a look at your code and will reply you shortly.
no problem, thanks for giving your time
hi, thanks for the tutorial. this work if im making an onsen ui + Angular Apple Iphone App? im trying to search and bring info from a data base into de app it self.
This should work.
How to protect database credentials in server.js?
You can encrypt it using any encryption algorithm.
I need your help ..
I wan talk to you once…over the phone
Thanks
Hi,
I am getting this error “Error: Bootstrap’s JavaScript requires jQuery” in index.html, so if I use
before bootstrap, I get this error
NetworkError: 404 Not Found – localhost/casablanca/angular-test/two-way-data-binding-demo-master/%7B%7Bdata.profile_picture%7D%7D”
Any clues?
Thanks!
Pablo.
I fixed by just running in localhost:3000 as you show in your video.
If I run it using XAMPP I get problems “CORS ‘Access-Control-Allow-Origin'”
Anyway running in port 3000 works perfectly.
Thanks a lot for this !!!!!
Cheers,
Pablo.
how we can take picture from local storadge
what about video !!!!
great tutorial! worked like charm with few hiccups around my sql app user permissions! Thanks a lot for putting this together!
Hi Shahid,
thank you for the great post.
I have one more question, what can I use instead of the server.js to avoid to expose database login info on a public host?
Just an hint would be fine.
Thanks