Home > Net >  How to initialize and update angular variable
How to initialize and update angular variable

Time:11-25

I have come across a scenario where I need to execute HTML inside ng-repeat conditionally after certain iterations.

Below is an example of that:

<div>
  <p ng-init="x=1">
    These are my names....
  </p>
  <div ng-repeat="a in data.result">
    <div ng-if="a.type=='Student' && x<3">
      <span ng-init="x  ">
         <br/>
        {{::a.name}} with type of {{::a.type}} and color {{::a.color}}
        </span>
    </div>    
  </div>  
</div>

Script:

data.result =[
  {
    "color": "Red",
    "name": "IP0",
    "type": "Student"
  },
  {
    "color": "Red",
    "name": "IPwd1",
    "type": "Student"
  },
  {
    "color": "White",
    "name": "IPdw2",
    "type": "Teacher"
  },
  {
    "color": "Red",
    "name": "IPed3",
    "type": "Student"
  },
  {
    "color": "Red",
    "name": "IP4ed",
    "type": "Student"
  },
  {
    "color": "White",
    "name": "IP7h2",
    "type": "Teacher"
  }
];  

The above code is always giving the below output:

**These are my names....
IP0 with type of Student and color Red
IPwd1 with type of Student and color Red
IPed3 with type of Student and color Red
IP4ed with type of Student and color Red**

I want the HTML to run only for the first 2 students only.

It seems 'x' is always initialized to 1 or not incrementing whenever it is executing the next loop. How can I make it run for some iterations conditionally? Any ideas?

image

CodePudding user response:

Here's a 'proper' way, though in this example is a tiny bit overkill. Rather than manipulate the original data source, you should use filters on your ng-repeat lists. To limit the result to a certain #, use limitTo. In the example below, the filter is scalable. You could make it filterBy:{type:'Student', color:'Red'} etc

The html:

<div ng-repeat="a in data.result | filterBy:{type:'Student'} | limitTo:2">
      {{::a.name}} with type of {{::a.type}} and color {{::a.color}}
</div> 

The angular filter

app.filter('filterBy', function() {
  return function(data, filters) {
    return data.filter(d => {
      let ret = true, x;
      for(x in filters) {
        if (d[x]!=filters[x]) ret = false;
      }
      return ret;
    })
  };
})

View the Plnkr:

https://plnkr.co/edit/g72UNjTgQUtofKqo?open=lib/script.js&deferRun=1

  • Related