1

I am creating an array like the following:

var arr =[];
arr['key1'] = 'value1';
arr['key2'] = 'value2';

If is use this array in ng-repeat tag, it is not displaying anything. Is there any way to make it work?

<div data-ng-repeat='(key,value) in arr'>{{key}} - {{value}}</div>

Is there any way to make it work?

4
  • Use an object rather than an array. Or better, use an array containing objects with a key attribute and a value attribute. That way you'll have a deterministic order. Make sure the array is on the scope. Commented Sep 26, 2015 at 11:55
  • ng-repeat should work as shown. You are actually creating object though when using non-numeric keys Commented Sep 26, 2015 at 11:56
  • 1
    @charlietfl, added a plunker here. Commented Sep 26, 2015 at 12:04
  • 1
    $scope.myArr = {}; ... works fine as declaring object Commented Sep 26, 2015 at 12:06

2 Answers 2

2

The way to go, is to creat plain object (instead of array)

// instead of creatin of an Array
// $scope.myArr = [];
// we just create plain object
$scope.myArr = {};
...
// here we just add properties (key/value)
$scope.myArr['attempt1'] = {};
...
// which is in this case same as this syntax
$scope.myArr.attempt1 = {};

Thee is updated plunker

Check more details what is behind for example here:

Javascript: Understanding Objects vs Arrays and When to Use Them. [Part 1]

Sign up to request clarification or add additional context in comments.

Comments

1

Your associative array is nothing but an object, as far as JavaScript is concerned. IMO Associative arrays and Objects are almost same.

Ex: Your arr['key1'] = 'value1'; can be called as console.log(arr.key1);

To make your code work, you need to change the array declaration by removing [] and replacing with {} (Curly braces)

Like this var arr = {};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.