Saturday 15 August 2015

AngularJS: ng-repeat an array with keys -


I have an array with unordered keys, and I want to display them. The problem is that angular repeats it for all the keys, even if they are not set.

This code is:

  & lt; Div ng-controller = "MyCtrl" & gt; Hello, {{One [10]}}! & Lt; P ng-repeat = "one in b" & gt; 1. {{B}} & lt; / P & gt; & Lt; / Div & gt; & Lt; Script & gt; Var myApp = angular.module ('myApp', []); MyCtrl ($ scope) function {$ scope.a = []; $ Scope.a [10] = "AAA"; } & Lt; / Script & gt;   

And this is the output:

  Hello, AAA! 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. aaa   

I want only array keys that are set to output. There is no blank b ....

Your problem is not related to AngularJS in short, but how the javascript works

If you have an empty array and if you assign an element to the position of 10, then javascript will automatically convert the array to 11 elements (because an array index starts with zero ) So that the index is enough to hold you the element.

You can write additional code to filter the empty elements, but depending on what you write, I think that you would be better off using the object to store your data.

I have created a plnkr for your convenience:

  // array $ scope.sampleArray = []; $ Scope.sampleArray [10] = 'test'; // object $ scope. Sampleobject = {}; $ Scope.sampleObject [10] = 'test';   

As you can see that syntax is very similar, but the output is completely different.

By using an object, you will automatically terminate the empty lines.

This keeps your code easy, because you will not have to deal with empty array elements.

Hope that helps!

No comments:

Post a Comment