Loops and Filters in angularJS (Part 2)

Here we are with the 2nd part of the tutorial, discussing about the loops and

filters. This is succeeded by another directive call ng-repeat. This is actually simple and very easy to understand. You will note it when we go through an example.

Create a index.html file and type the following code in it.

 

 

Name :

{{name}}

  • {{currentName}}

Same as the part 1 tutorial except 2 new directives are introduced here.

  •  ng-init – Initializes application data. Here it initializes an array of names.
  • ng-repeat – Uses to repeat an HTML element.

You will get the following output :)

3

So here is the code explanation,

  • Inside the body tag we have initialize an array with 3 elements. (As this is basic we are declaring it in the same file or in the view. We will use a controller or module latter).
  • Then we have a list, as you can see inside <li> tag ng-repeat directive is used.

    ng-repeat =”currentName in names”

    We now loop through each name (“currentName“) in “names” . When the ng-repeat runs for the first time takes the first value in the array and put in to the “currentName” then print it as a list item. Then comes to the second elements and goes until the last element of the array. (You can check it buy adding more values to the array)

Now let’s do something interesting 😉 . This is something like searching. You will output the same set of names as in the above example. But now you will filter the name you want by inputting a name in the textbox. Just edit the <ul> as follows,

 

  • {{currentName}}

Just check whether, you can filter names like in the following figure,(You can enter more names in to the array and check.)

4We just say it to filter a “name” from the “names” (“name“is the value given to ng-model in the textbox and “names” is the name of the array)

Now let’s improve the above code a little, try to filter with object. Here is the code,

 

Name :
{{name}}

  • {{person.name}} {{person.phone}}


We have a array with 2 types of details about a person in it. (Name and the phone number of a person)Just see and understand the way, how those data have been accessed.

In the next part, we will discuss about the controllers. Stay tuned guys.. :) :)

Sanjaya Thilakabandara

Information and Communication undergraduate in Rajarata University of Sri Lanka.

Leave a Reply

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