EzDevInfo.com

angularjs-ng-repeat interview questions

Top angularjs-ng-repeat frequently asked interview questions

Using comma as list separator with AngularJS

I need to create a comma-separated list of items:

  <li ng-repeat="friend in friends">
      <b ng-repeat="email in friend.email">{{email}}{{$last ? '' : ', '}}</b>...
  </li>

According to the AngularJS documentation, no control flow statements is allowed in expressions. This is why my {{$last ? '' : ', '}} does not work.

Is there an alternative way to create comma-separated lists?

EDIT 1
is there something simpler than:

<span ng-show="!$last">, </span>

Source: (StackOverflow)

how to split the ng-repeat data with three columns using bootstrap

I am using ng-repeat with my code I have 'n' number of text box based on ng-repeat. I want to align the textbox with three columns.

this is my code

<div class="control-group" ng-repeat="oneExt in configAddr.ext">
    {{$index+1}}. 
    <input type="text" name="macAdr{{$index+1}}" 
           id="macAddress" ng-model="oneExt.newValue" value=""/>
</div>

Source: (StackOverflow)

Advertisements

Preserve line breaks in angularjs

I have seen this SO question.

My code instead of ng-bind="item.desc" uses {{item.desc}} because I have a ng-repeat before.

So my code:

<div ng-repeat="item in items">
  {{item.description}}
</div>

The item description contains \n for newlines which are not rendered.

How can the {{item.description}} display the newlines easily assuming that I have the ng-repeat above?


Source: (StackOverflow)

angular ng-repeat skip an item if it matches expression

I'm looking for a way to basically tell angular to skip an item in an ng-repeat if it matches an expression, basically continue;

In controller:

$scope.players = [{
    name_key:'FirstPerson', first_name:'First', last_name:'Person'
}, {
    name_key:'SecondPerson', first_name:'Second', last_name:'Person'
}]

Now in my template I want to show everyone that doesn't match name_key='FirstPerson'. I figured it has to be filters so I setup a Plunkr to play around with it but haven't had any luck. Plunkr Attempt


Source: (StackOverflow)

Way to ng-repeat defined number of times instead of repeating over array?

Is there a way to ng-repeat a defined number of times instead of always having to iterate over an array?

For example, below I want the list item to show up 5 times assuming $scope.number equal to 5 in addition incrementing the number so each list item increments like 1, 2, 3, 4, 5

Desired result:

<ul>
   <li><span>1</span></li>
   <li><span>2</span></li>
   <li><span>3</span></li>
   <li><span>4</span></li>
   <li><span>5</span></li>
</ul>

Source: (StackOverflow)

orderBy multiple fields in Angular

How to sort by using multiple fields at same time in angular? fist by group and then by sub-group for Example

$scope.divisions = [{'group':1,'sub':1}, {'group':2,'sub':10}, {'group':1,'sub':2},{'group':1,'sub':20},{'group':2,'sub':1},
    {'group':2,'sub':11}];

I wanted to display this as

group : Sub-group

1 - 1

1 - 2

1 - 20

2 - 1

2 - 10

2 - 11

<select ng-model="divs" ng-options="(d.group+' - '+d.sub) for d in divisions | orderBy:'group' | orderBy:'sub'" />

Source: (StackOverflow)

using ng-repeat and ng-class on rows inside a table

I am using AngularJS and the effect I want to get would be something similar to what this would produce, assuming it would work (which it doesn't).

View

<tr ng-repeat='person in people' ng-class='rowClass(person)'>
  <td>.....info about person...</td>
  <td>.....info about person...</td>
  <td>.....info about person...</td>
</tr>

Controller

$scope.rowClass = function(person){
  ...return some value based upon some property of person...
}

I realise that this code won't work because person is unavailable to ng-class as it will only be available to objects inside each row. The code is to get the idea of what I'm trying to do across: ie. I want to be able to have table rows that are created using ng-repeat whose class is also based on a condition which depends on access to the scoped feature of row itself eg. person. I realise I could just add ng-class on the columns but that is boring. Anyone have any better ideas?


Source: (StackOverflow)

Using ng-if inside ng-repeat?

i am working on Angular app. I tried to use ng-if and switch inside ng-repeat but didn't succeed. I have data like:

   **[{"_id":"52fb84fac6b93c152d8b4569",
       "post_id":"52fb84fac6b93c152d8b4567",
       "user_id":"52df9ab5c6b93c8e2a8b4567",
       "type":"hoot",},  
      {"_id":"52fb798cc6b93c74298b4568",
       "post_id":"52fb798cc6b93c74298b4567",
       "user_id":"52df9ab5c6b93c8e2a8b4567",
       "type":"story",},        
      {"_id":"52fb7977c6b93c5c2c8b456b",
       "post_id":"52fb7977c6b93c5c2c8b456a",
       "user_id":"52df9ab5c6b93c8e2a8b4567",
       "type":"article",},**

$scope.comments = data mentioned above
and my Html like :

   <div ng-repeat = "data in comments">
      <div ng-if="hoot == data.type">
          //differnt template with hoot data
       </div>
      <div ng-if="story == data.type">
          //differnt template with story data
       </div>
       <div ng-if="article == data.type">
          //differnt template with article data
       </div> 
   </div>

How can i achieve this thing in Angular?


Source: (StackOverflow)

angularjs ng-style: background-image isn't working

I'm trying to apply a background image to a div by using the angular ng-style ( I tried a custom directive before with the same behaviour ), but it doesn't seem to be working.

<nav
    class="navigation-grid-container"
    data-ng-class="{ bigger: isNavActive == true }"
    data-ng-controller="NavigationCtrl"
    data-ng-mouseenter="isNavActive = true; $parent.isNavActive = true"
    data-ng-mouseleave="isNavActive = false; $parent.isNavActive = false"
    data-ng-show="$parent.navInvisible == false"
    data-ng-animate="'fade'"
    ng-cloak>

    <ul class="navigation-container unstyled clearfix">
        <li
            class="navigation-item-container"
            data-ng-repeat="(key, item) in navigation"
            data-ng-class="{ small: $parent.isNavActive, big: isActive == true }"
            data-ng-mouseenter="isActive = true; isInactive= false"
            data-ng-mouseleave="isActive = false; isInactive= true">

            <div data-ng-switch on="item.id">

                <div class="navigation-item-default" data-ng-switch-when="scandinavia">
                    <a class="navigation-item-overlay" data-ng-rel='nofollow' href="{{item.id}}">
                        <div class="navigation-item-teaser">
                            <span class="navigation-item-teaser-text" data-ng-class="{ small: isScandinavia }">{{item.teaser}}</span>
                        </div>
                    </a>
                    <span class="navigation-item-background" data-ng-style="{ 'background-image': 'public/img/products/{{item.id}}/detail/wide/{{item.images.detail.wide[0]}}' }"></span>
                </div>

                <div class="navigation-item-last" data-ng-switch-when="static">
                    <div class="navigation-item-overlay">
                        <div class="navigation-item-teaser">
                            <span class="navigation-item-teaser-text">
                                <img data-ng-src="{{item.teaser}}">
                            </span>
                        </div>
                    </div>
                    <span class="navigation-item-background">
                        <img class="logo" data-ng-src="{{item.images.logo}}">
                    </span>
                </div>

                <div class="navigation-item-default" data-ng-switch-default>
                    <a class="navigation-item-overlay" data-ng-rel='nofollow' href="{{item.id}}">
                        <div class="navigation-item-teaser">
                            <span class="navigation-item-teaser-text">{{item.teaser}}</span>
                        </div>
                    </a>
                    <span class="navigation-item-background" data-ng-style="{ 'background-image': 'public/img/products/{{item.id}}/detail/wide/{{item.images.detail.wide[0]}}' }"></span>
                </div>

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

Though, if I do try a background color, it seems to be working fine. I tried a remote source and a local source too http://lorempixel.com/g/400/200/sports/, neither worked.


Source: (StackOverflow)

Filtering an Angular 1.2 ng-repeat with "track by" by a boolean property

I'm trying to filter some list items based on the value of a boolean property, but no matter what I do the entire list is always displayed. A few of the the things I've tried have been so broken that nothing displays, but that's neither here nor there. I can't get my filtering working as desired:

$scope.attendees = [
     {"firstname":"Steve",    "lastname":"Jobs",  "arrived":true,  "id":1}
    ,{"firstname":"Michelle", "lastname":"Jobs",  "arrived":false, "id":2}
    ,{"firstname":"Adam",     "lastname":"Smith", "arrived":true,  "id":3}
    ,{"firstname":"Megan",    "lastname":"Smith", "arrived":false, "id":4}
    ,{"firstname":"Dylan",    "lastname":"Smith", "arrived":false, "id":5}
    ,{"firstname":"Ethan",    "lastname":"Smith", "arrived":false, "id":6}
];

Using the following ng-repeat filtering:

<ul>
    <li ng-repeat="person in attendees track by person.id | filter:arrived:'false'">
            {{person.lastname}}, {{person.firstname}}
    </li>
</ul>

I feel like I've tried every permutation that I can find referenced, most of which came from various StackOverflow search results:

  • filter:'arrived'
  • filter:arrived
  • filter:'person.arrived'
  • filter:person.arrived
  • filter:{arrived:true}
  • filter:{arrived:'true'}
  • filter:{person.arrived:true}
  • filter:{person.arrived:'true'}

I've also tried creating a custom filter function:

$scope.isArrived = function(item) {
    return item.arrived;
};

And applying it thusly:

  • filter:isArrived
  • filter:'isArrived'
  • filter:{isArrived(person)}
  • filter:isArrived(person)
  • filter:'isArrived(person)'

None of these seems to work. What am I missing?

Here's a plnkr that demonstrates my problem.


Source: (StackOverflow)

How to remove elements/nodes from angular.js array

I am trying to remove elements from the array $scope.items so that items are removed in the view ng-repeat="item in items"

Just for demonstrative purposes here is some code:

for(i=0;i<$scope.items.length;i++){
    if($scope.items[i].name == 'ted'){
      $scope.items.shift();
    }
}

I want to remove the 1st element from the view if there is the name ted right? It works fine, but the view reloads all the elements. Because all the array keys have shifted. This is creating unnecessary lag in the mobile app I am creating..

Anyone have an solutions to this problem?


Source: (StackOverflow)

Angular - Can't make ng-repeat orderBy work

I've tried many examples of ng-repeat with orderBy, but I can't make my json work with it.

<div ng-app>
    <script type="text/javascript" src="http://code.angularjs.org/1.0.1/angular-1.0.1.js"></script>
    <div ng:controller="Main">
        <div ng-repeat="release in releases| orderBy:'environment_id'">      
            {{release.environment_id}}
        </div>
    </div>
</div>

And the JSON

function Main($scope) {
$scope.releases = {
    "tvl-c-wbap001 + tvl-webapp": {
        "timestamp": " 05:05:53 PM ",
        "environment_id": "CERT5",
        "release_header": "Projects/Dev",
        "date": "19 Oct",
        "release": "12.11.91-1"
    },
    "tvl-c-wbap401 + tvl-webapp": {
        "timestamp": " 10:07:25 AM ",
        "environment_id": "CERT4",
        "release_header": "Future Release",
        "date": "15 Oct",
        "release": "485-1"
    },
    "tvl-c-wbap301 + tvl-webapp": {
        "timestamp": " 07:59:48 AM ",
        "environment_id": "CERT3",
        "release_header": "Next Release",
        "date": "15 Oct",
        "release": "485-1"
    },
    "tvl-c-wbap201 + tvl-webapp": {
        "timestamp": " 03:34:07 AM ",
        "environment_id": "CERT2",
        "release_header": "Next Changes",
        "date": "15 Oct",
        "release": "13.12.3-1"
    },
    "tvl-c-wbap101 + tvl-webapp": {
        "timestamp": " 12:44:23 AM ",
        "environment_id": "CERT1",
        "release_header": "Production Mirror",
        "date": "15 Oct",
        "release": "13.11.309-1"
    },
    "tvl-s-wbap002 + tvl-webapp": {
        "timestamp": " 12:43:23 AM ",
        "environment_id": "Stage2",
        "date": "15 Oct",
        "release": "13.11.310-1"
    },
    "tvl-s-wbap001 + tvl-webapp": {
        "timestamp": " 11:07:38 AM ",
        "environment_id": "Stage1",
        "release_header": "Production Mirror",
        "date": "11 Oct",
        "release": "13.11.310-1"
    },
    "tvl-p-wbap001 + tvl-webapp": {
        "timestamp": " 11:39:25 PM ",
        "environment_id": "Production",
        "release_header": "Pilots",
        "date": "14 Oct",
        "release": "13.11.310-1"
    },
    "tvl-p-wbap100 + tvl-webapp": {
        "timestamp": " 03:27:53 AM ",
        "environment_id": "Production",
        "release_header": "Non Pilots",
        "date": "11 Oct",
        "release": "13.11.309-1"
    }
}

It doesn't matter what I write, I always get the same order, or I may say, no order at all.

Please, help!

Thanks!


Source: (StackOverflow)

Angular JS hide first element of ng-repeat

How would I hide the first element of an ng-repeat?

<div ng-repeat="item in items" ng-hide="true">
    <div>{{ item.value }}</div>
</div>

This works in that the whole ng-repeat block is hidden, but how would I hide only the first item in items? I want to display it completely differently using more prominent html/etc, so it's useful to have it in that list of data.


Source: (StackOverflow)

AngularJS multiple filter with custom filter function

I am trying to filter the list with multiple filters + with a custom filter function.

The original working jsfiddle example is http://jsfiddle.net/ed9A2/1/ but now I want to change the way age are being filter.

I want to add a custom filter so that age it filter based on two input value which is min_age and max_age , (between age) .

After looking into doc. I found people having similar questions and a user Mark Rajcok answer http://docs.angularjs.org/api/ng.filter:filter#comment-648569667 looks good and should be working. But I am having problem applying it into my codes which mainly seems to because I have other multiple filters.

Im very new to AngularJS :(

My tried and NOT working fiddle is here http://jsfiddle.net/ed9A2/20/

A copy paste of my NOT working codes are here

View

<div ng-app ng-controller="MainController">
<table class="fancyTable">
    <tr>
        <th>Player id</th>
        <th>Player name</th>
        <th>Age</th>
    </tr>
    <tr>
        <td><input ng-model="player_id" /></td>
        <td><input ng-model="player_name" /></td>
        <td>
            Min Age:<input ng-model="min_age" />
            Max Age:<input ng-model="max_age" />
        </td>
    </tr>
    <tr ng-repeat="player in players | filter:{id: player_id, name:player_name, age:ageFilter}">
        <td>{{player.id}}</td>
        <td>{{player.name}}</td>
        <td>{{player.age}}</td>
    </tr>
</table>

Controller

function MainController($scope) {

$scope.player_id = "";
$scope.player_name = "";
$scope.player_age = "";
$scope.min_age = 0;
$scope.max_age = 999999999;

$scope.ageFilter = function(player) {
    return ( player > $scope.min_age && player.age < $scope.max_age);
}

$scope.players = [
        {"name": "Rod Laver",
            "id": "rod",
            "date": "1938/8/9",
            "imageUrl": "img/rod-laver.gif",
            "age": 75},
        {"name": "Boris Becker", 
            "id": "borix",
            "date": "1967/11/22",
            "imageUrl": "img/boris-becker.gif",
            "age": 45},
        {"name": "John McEnroe",
            "id": "mcenroe",
            "date": "1959/2/16",
            "imageUrl": "img/john-mc-enroe.gif",
            "age": 54},
        {"name": "Rafa Nadal",
            "id": "nadal",
            "date": "1986/5/24",
            "imageUrl": "img/ndl.jpg",
            "age": 27}
    ]
}

Source: (StackOverflow)

Do bindings nested inside of a lazy one-time ng-repeat binding bind just once?

My understand is that in the following code, both bindings will lazily bind only once:

<li ng-repeat="item in ::items">{{::item.name}}</li>

However, in the following case will {{item.name}} be updated every digest?

<li ng-repeat="item in ::items">{{item.name}}</li>

And how does one-time binding affect nested ng-repeats ?

<li ng-repeat="item in ::items">
  <span ng-repeat="thing in item.things">{{thing.name}}</span>
</li>

Source: (StackOverflow)