Sunday, 19 March 2017

How to initialize values using ng-init ?


ng-init evaluates an expression in current scope.

HTML
<div ng-init="
employees = [
        { name : "Shaan", gender : "Male",   salary : 25000 },
        { name : "Renu",  gender
: "Female", salary : 47000 },
        { name : "Rahul", gender
: "Male",   salary : 35000 },
        { name : "Anju",  gender
: "Female", salary : 18000 }
    ]
"
>

 
  <table>
     <thead>
        <tr> <th>Name</th> <th>Gender</th> <th>Salary</th> </tr>
     </thead>
     <tbody>
        <tr ng-repeat="employee in employees">
           <td> {{ employee.name }} </td>
           <td> {{ employee.gender
}} </td>
           <td> {{ employee.salary }} </td>
        </tr>
     </tbody>
  </table>
</div>



 

CORRECT USE OF ng-init
  • In real world projects, always Controllers are used for initializing the values on scope, instead of ng-init
    So, above implementation can be done but not recommended

  • ng-init should only be used for making alias for special properties of ng-repeat directive.

EXAMPLE

<body ng-app="module1"> <div ng-controller="myController"> 
  <ul>
     <li ng-repeat="course in courses"  ng-init="parentIdx=$index">
        
{{ $index }} {{ course.name }}
         <ul>
           <li ng-repeat="subject in course.subjects">
               
{{ parentIdx }} {{ $index }} {{ subject.name }}
           </li>
         </ul>

     </li>
  </ul>
</div> 

OUTPUT
  • 0 BCA
    • 0 0 Fundamentals
    • 0 1 C
    • 0 2 C++
  • 1 MCA
    • 1 0 Java
    • 1 1 VB
    •     ...

No comments:

Post a Comment

Note: only a member of this blog may post a comment.