AngularJS (ng-model, ng-repeat)

ng-model

In two way data binding in Angular,  when the model changes, the View is automatically updated. This is achieved using the data binding expression in the View.

Script.js

The code in the Controller attaches message property to the scope which is the Model. 

  1. var app = angular.module("myModule", []).controller("myController"function($scope) {  
  2.     $scope.message = "Hello Angular! I am a beginner"  
  3. });   

HtmlPage1.html

Whenever the message property value changes, the data binding expression in the View updates the View automatically. 

  1. <!DOCTYPE html>  
  2. <html xmlns="http://www.w3.org/1999/xhtml">  
  3.   
  4. <head>  
  5.     <title></title>  
  6.     <script src="Scripts/angular.min.js"></script>  
  7.     <script src="Scripts/Script.js"></script>  
  8. </head>  
  9.   
  10. <body ng-app="myModule">  
  11.     <div ng-controller="myController"> {{ message }} </div>  
  12. </body>  
  13.   
  14. </html>   

How about the other way around? 

How to keep the Model up to date when the View changes. That's exactly the purpose of ng-model directive.

In the HTML below, notice that the input element is decorated with ng-model directive. This ensures that whenever the value in the textbox changes, Angular will automatically update the message property of the $scope object. This means the ng-model directive automatically takes the form values and updates the Model. The binding expression does the opposite, i.e whenever the model changes, the View is automatically updated.

Because of the two way data binding provided by Angular, as you type in the textbox, the value is immediately displayed on the View just below the textbox. This eliminates the need to write any custom code to move data from the Model to the View or from the View to Model. 

  1. <!DOCTYPE html>  
  2. <html xmlns="http://www.w3.org/1999/xhtml">  
  3.   
  4. <head>  
  5.     <title></title>  
  6.     <script src="Scripts/angular.min.js"></script>  
  7.     <script src="Scripts/Script.js"></script>  
  8. </head>  
  9.   
  10. <body ng-app="myModule">  
  11.     <div ng-controller="myController"> <input type="text" placeholder="Type your message here" ng-model="message" /> <br /><br /> {{ message }} </div>  
  12. </body>  
  13.   
  14. </html>  

ng-model directive can be used with the following 3 HTML elements

  • input
  • select
  • textarea

ng-repeat

ng-repeat is similar to foreach loop in C#.

Finding the index of an item in the collection,

  • To find the index of an item in the collection use $index property.
  • To get the index of the parent element

    • Use $parent.$index or
    • Use ng-init="parentIndex = $index".
Next Recommended Reading How To Use Nested ng-repeat In AngularJS