AngularJS ng-model

FYLN4CE6C7 I can use the ng-model directive on an input variable to automatically bind the input to the element for display.


<html ng-app>
  <head>
    <link rel="stylesheet" href="css/bootstrap.css">
    <script type="text/javascript" src="angular.min.js"></script>
    <script type="text/javascript" src="bootstrap.min.js"></script>
  </head>
  <body style="padding: 50px">
    <div class="alert alert-info" ng-init="myvar = 'Hello World!'">
      <p>
	<input type="text" ng-model="myvar" size="20" />
      </p>
	Here it is: "{{ myvar }}"
    </div>
  </body>
</html>

Notice the ng-init = "myvar = 'Hello World!'" on the div. This initializes the myvar variable.

The ng-model="myvar" on the input binds the myvar variable to the input so that whatever is typed in the input field will automatically be bound to that variable.

The {{ myvar }} will automatically output the myvar variable whenever data is entered on the form.

Click the ‘Result’ tab below to see how it looks on a web page. Replace the information in the text box and it will automatically change the line below it:

Leave a Comment

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

Scroll to Top