Two way data binding angularjs tutorial

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.

LIVE DEMO DOWNLOAD

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.

Two way data binding

We are going to use Node as back-end which handle the operation with MySQL. Data will be passed using JSON format.

Project Architecture.

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‘.

MySQL table

Create two rows with the proper name as shown below.

rows

Once done. Go to SQL tab and insert some demo rows. Here are some which i used while developing the app.

INSERT INTO `user_info`(`profile_picture`) VALUES
('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.

Package.json
{
"name": "two-way-data-binding",
"version": "1.0.0",
"dependencies": {
"express": "~4.9.2",
"mysql": "~2.5.0"
}
}

Install dependencies using

npm install

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.

Server.js
var express = require("express");
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.

Server.js
app.get('/',function(req,res){
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

node Server.js

I use postman chrome extension to simulate the API calls. Here is what i got after calling /load API.

postman

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.

app.js
var app=angular.module('two_way',[]);

here is controller code.

core.js
app.controller('two_way_control',function($scope,$http,$interval){
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.

index.html
<html>
  <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.

Shahid (UnixRoot) Shaikh

Hey there, This is Shahid, an Engineer and Blogger from Bombay. I am also an Author and i wrote a programming book on Sails.js, MVC framework for Node.js.

Related Posts

50 Comments

  1. 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

      1. There is a problem when you typing the url : ‘http://localhost:3000/load’
        it displays all informations in database

  2. 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.

  3. 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.

    1. 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.

      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.

  4. 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?

  5. 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 http://localhost:3306/load. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

  6. 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

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

  8. 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.

    1. I fixed by just running in http://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 perfect.

      Thanks a lot for this !!!!!

      Cheers,

      Pablo.

  9. great tutorial! worked like charm with few hiccups around my sql app user permissions! Thanks a lot for putting this together!

Leave a Reply

Your email address will not be published. Required fields are marked *