One Way Binding in AngularJS

Here I have to show, how data binding One Way using Angular JS and why say One Way.

One way data binding means, we have fixed data value and use that value to show on browser. All of you know that, Angular JS is a MVC architechure and developed by Google.

Here I have used Angulur JS plugin to get its functionality.

I have created a page in notepad and named this OneWayBinding.html, you can use any type of editor to write this code.

I have added AngularJS plugin in head section and page looks like below-

OneWayBinding.html

  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4. <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>   
  5. </head>  
  6. <body>  
  7. </body>  
  8. </html>  
Now add body part who show on browser:
  1. <body ng-app ng-init="firstName = Upendra; lastName = Shahi;">  
  2. <strong>First name:</strong> {{firstName}}<br />  
  3. <strong>Last name:</strong> <span ng-bind="lastName"></span>  
  4. </body>  
Directives:

Every HTML attribute specific to AngularJS is called directive and has a specific role in an AngularJS application(SPA).

Here I have used ng-app directive to get the AngularJS functionality. ng-app directives marks the DOM element which contains AngularJS application.

I have used another directive as ng-init to initialize the value. Here I have initalised two variable 'firstname' and 'lastName'
.
now whole page looks like:
  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4. <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>   
  5. </head>  
  6. <body ng-app ng-init="firstName = Upendra; lastName = Shahi;">  
  7. <strong>First name:</strong> {{firstName}}<br />  
  8. <strong>Last name:</strong> <span ng-bind="lastName"></span>  
  9. </body>  
  10. </html>  
A data binding may be as below:

  • with curly braces: {{expression}}
  • with the ng-bind directive : ng-bind="varName"

Save page and run over any browser and see below output.

OutPut:

First name:
Upendra
Last name: Shahi

Summary:

We're saying one way data binding because the model values ( variables represent the model) are automatically assigned to the HTML placeholder elements specified through the data binding notation, but the HTML elements don't change the values in the model (one way).

Above was some information regarding AngularJS. I hope all you have enjoyed article and I welcome your feedback.

Ebook Download
View all
Learn
View all