Mark
Mark

Reputation: 2587

Angular.js ng-repeat with conditional

I'm using ng-repeat to iterate over a key/value array. If the key == 'First Name' I would like to bind it to firstName. I'm new to angular.js, there may be a better way to do this? Basically I have a key/value array and some of the key's in it I would like to do something with.

<ul id="customers" infinite-scroll='loadMoreUsers()'>
        <li ng-repeat="user in users" data-customer-id="{{user.Id}}">

               <h4>{{user.firstName}} {{user.lastName}}</h4>

            <div ng-repeat="(key, value) in user.AttributeBag">
                <span ng-if="key == 'First Name'">{{user.firstName = value}}</span>
                <span ng-if="key == 'Last Name'">{{user.lastName = value}}</span></span>

                <span ng-if="key != 'First Name' && key != 'Last Name'">{{key}} : {{value}}</span>
            </div>
        </li>
    </ul>

Upvotes: 0

Views: 489

Answers (2)

danday74
danday74

Reputation: 56936

source : http://www.w3schools.com/js/js_arrays.asp

JavaScript does not support arrays with named indexes. In JavaScript, arrays always use numbered indexes. WARNING !! If you use a named index, JavaScript will redefine the array to a standard object. After that, all array methods and properties will produce incorrect results.

var person = [];
person["firstName"] = "John";
person["lastName"] = "Doe";
person["age"] = 46;
var x = person.length;         // person.length will return 0
var y = person[0];             // person[0] will return undefined

possibly what your are doing is conceptually wrong and you need to use an array of objects?

Upvotes: 1

Danny
Danny

Reputation: 624

ng-if creates it's own child scope which is why you can't access the key

Two approaches I can think of

  1. Use ng-show instead of ng-if. ng-show does not create it's own scope.
  2. Use $parent to access the parent scope. However you are using an abstraction of the user.AttributeBag in your ng-repeat so this will need some tweaking.

Upvotes: 1

Related Questions