What is ng-model in Angular JS and How to use it?

By | June 17, 2017

With the ng-model directive you can bind the value of an input field to a variable created in AngularJS.

Here we will have two input fields which will bind to two variables in Angular JS.

Example

<html">
    
   <head>
      <title>Angular JS Controller</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
   </head>
    
   <body>
      <h2>AngularJS Demo Application</h2>
       
        
      <div ng-app="MyApp" ng-controller="MyController" ng-init="test()">
       
       Enter first name: <input type = "text" ng-model = "firstName"><br /><br />
       Enter last name: <input type = "text" ng-model = "lastName"><br /><br />
       
      {{ firstName + " " + lastName }}
       
      </div>
      
    <script>
          
      var app = angular.module("MyApp", []);
      app.controller("MyController", function($scope){
       
        $scope.firstName = "Coderz";
        $scope.lastName = "Heaven";
                 
      });
 
 
      </script>
       
   </body>
</html>

Just copy paste the above code to your editor and save in html and see the result.

Leave a Reply

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