Constructing variable names in AngularJS while using ng-repeat

I am working with a series of items that are structured as described below. Unfortunately, I do not have control over the variable names.

pubDate0, pubDate1, pubDate2

To access them, I currently use the following format:

<div>
   <i>
      {{newsData.pubDate0[0]}}
   </i>
</div>
<div>
   <i>
      {{newsData.pubDate1[0]}}
   </i>
</div>
<div>
   <i>
      {{newsData.pubDate2[0]}}
   </i>
</div>

Is there a way to concatenate these variable names using ng-repeat in order to avoid writing repetitive code?

I have attempted various approaches within an ng-repeat loop, but none have been successful.

<p ng-repeat="t in getTimes(10) track by $index"> //looping 10 times
    {{(newsData.pubDate+$index+[0])}}
</p>

//Some of the attempts made:
{{(newsData.pubDate+$index+[0])}}
{{('newsData.pubDate'+$index+[0])}}
{{('newsData.pubDate'+$index+'[0]')}}
{{newsData.pubDate+$index+[0]}}
{{newsData.pubDate+($index)+[0]}}
{{newsData.pubDate+{{$index}}+[0]}}
{{newsData.pubDate($index)[0]}}
{{newsData.pubDate$index[0]}}
{{newsData.pubDate{{$index}}[0]}}
{{newsData.pubDate+$index+[0]}}

Feeling somewhat stuck at this point. :(

Answer №1

There are a couple of methods to access a JavaScript property:

var obj = {prop1: 'p1', prop2: 'p2'};
console.log(obj.prop1); //p1

var propName = 'prop';
var index = 1;
console.log(obj[propName + index]); //p1

It is recommended to use the second approach:

newsData['pubDate'+$index][0];

JSFIDDLE.

Answer №2

If you want to easily achieve this, simply use new Array(10) if you already know the length. See the code below:

//Controller:
$scope.getTimes = function(x) {
   return new Array(x);
}

<p ng-repeat="t in getTimes(10) track by $index"> //loop through 10 times
    {{(newsData['pubDate'+$index][0])}}
</p>

However, I recommend converting the data the way you prefer before resolving the promise or assigning it to the scope, especially if you plan on using the data throughout your application.

If the following code represents your service call:

        var getAllNews = function() {
            var deferred = $q.defer();

            $http.get('/api/news')
            .success(function (resultNews) {
                var pubDates = []; //will be new pubDate array
                for (var key  in resultNews) {
                   //check if it is a pubDate
                   if (key.indexOf("pubDate") === 0) {
                      pubDates.push(resultNews[key]); // add it to array
                      delete resultNews[key]; // remove from the object
                   }
                }
                //finally assign new array as a property of result
                resultNews.pubDates = pubDates;
                deferred.resolve(resultNews);
            });

            return deferred.promise;
        };

It's worth noting that the second approach may have issues with the order of items due to browsers not promising to return them in order, even if they are.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Getting the highest level object in a nested Angular component structure

Currently, I am in the process of developing a query builder using Angular that bears resemblance to the JQuery builder. However, I have encountered an issue related to emitting the data. Whenever I click on the addGroup or addRule buttons, a new group is ...

Is it recommended to rely on Javascript for altering the content of a div across an entire website?

I am in the process of creating my personal portfolio and have a few inquiries regarding the framework to implement. Currently, I have an index.html page that contains all the information I want displayed when visitors land on the site. Additionally, ther ...

An error has occurred with TokBox: OT.Session is unable to connect because the session has already been declared as

I encountered a similar issue but I'm struggling to make sense of what's going on. I have created a .Net page that includes all the necessary TokBox methods for subscribing. The process involves launching a new window (video monitor for multiple ...

I would like the capability to choose a roster of gods depending on a character's class and moral orientation

I am in the process of developing a character sheet for Dungeons & Dragons, and I'm looking to pass the values from two drop-down menus into a query that will then populate another select list. Despite trying various methods to retrieve the data, I ke ...

modify the navigation when router events are triggered

Is there a way to modify the destination route after the router events have been triggered in an Angular app? I am trying to implement a functionality where if the user clicks the browser back button, the navigation is redirected to the home page. However, ...

How do I easily show/hide a submenu in AngularJS with a toggle menu?

After browsing some Stacks, I've come to the realization that I need to create separate directives in order to hide or toggle a menu from its sub-menu items. I want the menu to be hidden when any of the sub-menu items are clicked. However, I can&apo ...

What is the mechanism behind the jQuery ready function that enables its first parameter to transform into a jQuery object?

While browsing today, I came across this interesting code snippet: jQuery(document).ready(function($$){ console.log($$); }); It seems that $$ is recognized as the jQuery object itself. Typically, to achieve this, we would need to pass the jQuery varia ...

Variable Returned by AJAX

I am attempting to send a variable using a select box via POST method, then use AJAX to submit the data and finally leverage that variable on the original page to update SQL queries. Below is the code snippet I currently have: <script type="text/j ...

I attempted to generate a 3x3 matrix and use ng-repeat to display the data, but unfortunately, the code is

This is the reply I received from the server. "data": [ { "id": 1, "ticket": "[ [\"5\",\"11\",\"24\",null, ...

Unusual perspective of JSON with ng-jsoneditor in AngularJS

Currently, I have integrated ng-jsoneditor into my AngularJS application to display and format JSON data. I found guidance on how to implement this from both here and here. Here is the HTML code snippet: <div ng-jsoneditor="onLoad" ng-model="vm. ...

Is it possible to interact with a particular point or element within a canvas using languages like javascript, jquery, or selenium?

I am trying to figure out how to simulate a click at a specific position within a canvas. I have tried using coordinates, but so far haven't found a way to make it work. Any other suggestions would be greatly appreciated. It's important to note t ...

Highlight the parent item when the child item is being hovered over

I am working on a menu that has 2 submenus. I want to use jQuery to highlight the item when it is hovered over. However, I am struggling with how to also highlight the parent item when the cursor is on the child item. The class I am using for highlighting ...

Switch up the side navigation panel display

Hello, I am a newcomer to bootstrap and I have successfully implemented a collapsing navbar. However, I am looking for a way to make the navbar slide out from the right side when clicked on in mobile view. Can someone provide me with some JavaScript or j ...

Creating a dedicated login page separate from the single page application structure

My angularJS single page application functions as an admin dashboard, but I want to restrict access to only logged-in users. The issue I am encountering is that when I create a login template, it typically blends in with the admin dashboard due to the natu ...

Invoke a separate function after a successful Ajax request

I am currently working on an AJAX call in MVC3 and here is the snippet of code I have: save: function () { $.ajax({ url: "@Url.Action("Save")", type:"post", data: ko.toJSON(this), contentType:"applic ...

Resolving issues with JavaScript caused by Polymer updates

I am a novice when it comes to working with Polymer. From what I have gathered, there seems to be compatibility issues with Mozilla and Safari. After researching on StackOverflow, I found that adding addEventListener('WebComponentsReady', funct ...

What is the method for incorporating choices into a schema field in Mongoose?

If my Schema is like this: var fooSchema = new Schema({ foo: String }); and I'm looking to implement select: false for foo, how can I achieve this without altering the initial structure? var fooSchema = new Schema({ foo: { type: String, select: ...

Using Python Selenium to create a login page with Javascript

Attempting to access a page using Python selenium package for certain activities is proving challenging. Despite the following code being written, an error message of "the Class is not found" keeps appearing. To proceed with using send_keys(), it's ne ...

Simplified user interface for detecting radio button clicks

Currently working on a form that includes radio buttons, where an update function is triggered whenever there is a user input change. The challenge I am facing is how to incorporate user-friendly radio buttons with a larger button area encompassing both t ...

"Obtain permission from Azure Graph to fetch details for a specific user using their principal

Here is the Node.js code snippet: const GraphkManagementClient = require('azure-graph'); client = new GraphkManagementClient(credentials, tenantId); client.users.get(principalID); The last line triggers an error message: Authorization_Reques ...