AngularJS Framework : Binding
Let's start by setting up a div with an ng-app attribute. This attribute says that this element (the div) and everything inside of it belongs to this app.
<!DOCTYPE html> <html> <head> <title>AngularJS Example</title> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script> </head> <body> <div ng-app=""> </div> <script type="text/javascript" src="vendor/angular.js"></script> </body> </html>
Binding can be represented in AngularJS using the ng-bind directive or with double curly brackets. For example, we can use expressions in our div:
<!DOCTYPE html> <html> <head> <title>AngularJS Example</title> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script> </head> <body> <div ng-app=""> 2016 {{" " + "bogotobogo" + "." + "com"+ "'s "}} AngularJS </div> </body> </html>
If we render the html file, we get:
Binding is most useful when we create an input or a way for the user to interact with a site of our app.
Let's create an input with an attribute ng-model which is set to "message" and then bind it inside our div:
<!DOCTYPE html> <html> <head> <title>AngularJS Example</title> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script> </head> <body> <div ng-app=""> <input type="text" ng-model="message"> <h1>{{message}}</h1> </div> </body> </html>
If we render the html file, we get:
Now when we load the page, if we start typing in the input field, we will see that the model has been bound and our text will start showing up as we type.
Now we can actually changes the class of the div and the div gets styled differently. So, we can manipulate a lot of the dom using binding, not just presenting simple text.
<!DOCTYPE html> <html> <head> <title>AngularJS Example</title> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script> </head> <body> <div ng-app=""> <input type="text" ng-model="message"> <h1>Hello {{message}}!</h1> <div class="{{message}}"> class ... </div> </div> </body> </html>
AngularJS
Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization