Array problems in angularjs

2

I'm having a 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 have already checked if some function is changing the value of my_array but it does not. And even if it had something like that it was not for {{ my_array['lorem'] }} to work ...

    
asked by anonymous 22.01.2015 / 11:04

2 answers

3

I do not understand if you really want to create an array or an object. In the example you mentioned, you are creating an object. In javascript you can access the properties of objects by name.

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

This would be a valid notation in your angle code:

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

But this is more semantic and makes it easier to read:

{{ my_obj.lorem.name }}

You can still use both forms like this:

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

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

To declare an array you would do it this way:

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

However, 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 name property:

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 a yes object, almost that initial idea, but a little simpler. So:

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

Accessing:

{{ my_obj['lorem'] }} ou {{ my_obj.lorem }}
    
24.03.2015 / 13:20
1

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

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

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

Example in code: JSFIDDLE

    
22.01.2015 / 21:48