Problems with array in Angularjs

Asked

Viewed 848 times

2

I have a certain problem filling an array and then returning it. For example:

JS

var my_array = {'teste':{'name':'Teste 123'},'lorem':{'name':'Lorem Ipsum'}};
// Esse valor é preenchido pelo $http.post()

HTML

{{ my_array }} // Retorna vazio: []
{{ my_array['lorem'] }} // Retorna {'name':'Lorem Ipsum'}

I’ve checked if any function is changing the value of my_array but there isn’t. And even if there was something like that it wasn’t meant to {{ my_array['lorem'] }} work ...

  • What do you expect {{ my_array }} exhibit? Maybe you want to {{ my_array.length }}.

  • Javascript arrays are different from objects, arrays are declared as my_array = [] and objects such as my_array = {}. Arrays have only numeric indices. To view the object you can use the native angular json filter {{ my_array | json }}

2 answers

3

I don’t understand if you really want to create an array or an object. In the example you quoted you are creating an object. In javascript you can access object properties by name.

var my_obj = {'teste':{'name':'Teste 123'},'lorem':{'name':'Lorem Ipsum'}};

That would be a valid notation in your angular code:

{{ my_obj['lorem']['name'] }}

But this is more semantic and facilitates reading:

{{ my_obj.lorem.name }}

It is still possible to use both forms so:

{{ my_obj['lorem'].name }}

Maybe you’re confusing it with an array because of this (I think it’s what you’re looking for).

To declare an array you would do so:

var my_array = [{'name' : 'Teste 123' }, { 'name' : 'Lorem Ipsum' }];

But the arrays can only be accessed by the index:

{{ my_array[0].name }} //acessando o primeiro elemento

To declare a simple list of strings, you could avoid the property name:

var my_array = ['Teste 123', 'Lorem Ipsum'];

Accessing:

{{ my_array[0] }} //acessando o primeiro elemento

Finally, if you want to create a simple list of strings that can be accessed by an indexer name, the solution would be to create an object yes, almost your initial idea, but a little simpler. Thus:

var my_obj = { 'teste': 'Teste 123', 'lorem': 'Lorem Ipsum' };

Accessing:

{{ my_obj['lorem'] }} ou {{ my_obj.lorem }}

1

There you wrote the array in the wrong format, the correct would be like this:

$scope.my_array = [{'teste':{'name':'Teste 123'}},{'lorem':{'name':'Lorem Ipsum'}}]

a list of objects always have to use the "[]" example: [{...},{...},{...},{...}]

Example in the code: JSFIDDLE

Browser other questions tagged

You are not signed in. Login or sign up in order to post.