Book Image

Data Oriented Development with Angularjs

Book Image

Data Oriented Development with Angularjs

Overview of this book

Table of Contents (17 chapters)
Data-oriented Development with AngularJS
Credits
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Preface
Index

Two-way data binding


Let's extend the preceding example to illustrate two-way data binding:

<!DOCTYPE html>
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.17/angular.min.js"></script>
  <title>AngularJS - Two way data binding</title>
</head>
<body>
  <div ng-app>
    <div>
      <h2 style="color:blue;">One way data binding? Cool!</h2>
      <label>Name:</label>
      <input type="text" ng-model="yourName" placeholder="Enter a name here">
      <h3>Hello {{yourName}}!</h3>
    </div>
    <hr />
    <div>
      <h2 style="color:green;">Two way data binding? Great!</h2>
      <textarea type="text" ng-model="newName" placeholder="Enter some text to change the value of the underlying model"></textarea>
      <button ng-click="yourName = newName">
        Change the underlying model's value
      </button>
    </div>
  </div>
</body>
</html>

(two-way-data-binding.html)

  • We've made very few changes to our preceding Hello World example. We introduced a <textarea> element and bound it to a new model variable called newName.

  • We added a <button> element, and we are handling its clicked event (using the ngClick directive). Inside the click event, we just assigned the value of the newName new model to our old variable yourName.

  • As soon as you enter some text in the textarea value and click on the Change the underlying model's value button, the textarea value is reflected in the Name textbox and the Hello label.

  • This shows two-way data binding in action. The UI control reflects the value of the underlying model and vice versa.