How to iterate over an array and assign values to distinct labels using AngularJS

Challenge


My goal is to present the user with information about their upcoming 4 events. I have used splice on an array to extract the first 4 objects. Now, I need to iterate through these objects and display the relevant data.

Each label is unique and will contain distinct names.

I am unsure if my current approach is correct as this project serves as a learning experience for me.

Snippet


Below is a part of my ASP.NET code that showcases the 4 events:

<div class="row" style="padding-top: 10px; padding-bottom: 10px; border: 1px solid #ddd; border-radius: 2px; margin-top: 25px; border-left: 4px solid #21cd25; font-size: 12px;">
    <div class="col-lg-12">
        <span class="glyphicon glyphicon-ok" style="color: #21cd25; padding-right: 10px;"></span>
        <span style="font-weight: 500;">10 Days - </span>
        <span>Holiday</span>
    </div>
</div>
<!-- Additional event rows removed for brevity -->

The labels provide details such as days left until the event and the type of event itself.

Function in Controller:

function GetNext4UserEvents() {

    var top4 = _allUserEvents.splice(0, 4);

}

I haven't made significant changes to this function as I'm still exploring the best approach. However, it successfully extracts the top 4 objects from the data.

An example object structure is shown below:

0: Object
    color: "#cc0000"
    end: "2016-02-20"
    id: 6
    start: "2016-02-10"
    title: "Test2"

Answer №1

It’s possible that I may have misunderstood your inquiry, but here is an attempt to display your events. While it might not align perfectly with your expectations, it could serve as a good starting point. I’ve set up a jsFiddle for you to experiment with the code.

HTML:

<div ng-app="app">
  <div ng-controller="ctrl">
    <div class="row" style="padding-top: 10px; padding-bottom: 10px; border: 1px solid #ddd; border-radius: 2px; margin-top: 25px; border-left: 4px solid #21cd25; font-size: 12px;" ng-repeat="event in sampleEvents">
      <div class="col-lg-12">
        <span class="glyphicon {{event.color | findIcon}}" ng-style="{'color': event.color, 'padding-right': '10px'}"></span>
        <span style="font-weight: 500;">{{event.start | daysOut}} - </span>
        <span>{{event.title}}</span>
      </div>
    </div>
  </div>
</div>

JS:

angular.module("app", ["angularMoment"])
  .filter("daysOut", function(moment) {
    return function(input) {
      return moment.duration(moment(input) - moment()).humanize();
    };
  })
  .filter("findIcon", function() {
    return function(input) {
      switch (input) {
        case "#cc0000":
          return "glyphicon-remove";
          break;
        case "#008000":
          return "glyphicon-ok";
          break;
        case "#ffa500":
          return "glyphicon-question-sign";
          break;
      }
      return "glyphicon-ok";
    }
  })
  .controller("ctrl", function($scope) {
    $scope.sampleEvents = [{
      color: "#cc0000",
      end: "2016-04-01",
      id: 1,
      start: "2016-03-19",
      title: "Event 1"
    }, {
      color: "#008000",
      end: "2016-04-03",
      id: 2,
      start: "2016-03-22",
      title: "Event 2"
    }, {
      color: "#ffa500",
      end: "2016-04-15",
      id: 3,
      start: "2016-04-02",
      title: "Event 3"
    }, {
      color: "#008000",
      end: "2016-04-14",
      id: 4,
      start: "2016-03-13",
      title: "Event 4"
    } ];
  });

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

Effectively accessing the Templater object within a user script for an Obsidian QuickAdd plugin

I have developed a user script to be used within a QuickAdd plugin Macro in Obsidian. The Macro consists of a single step where the user script, written in JavaScript following the CommonJS standard, is executed. Within this script, there is a task to gene ...

Accessing the current state outside of a component using React Context

As I delve into creating a React application, I find myself in uncharted territory with hooks and the new context API. Typically, I rely on Redux for my projects, but this time I wanted to explore the context API and hooks. However, I'm encountering s ...

Which nodejs versions are compatible with async Iterators?

Which iterations of nodejs are compatible with async Iterators? Can it be adapted to function on previous versions of nodejs? usage for await (let content of promises) { // promises => array of promise objects console.log(content); } ...

Fetching data using ajax and then appending it to the webpage

I am currently loading content from a PHP file in JSON format. products.php <?php $stmt = $mysqli->prepare("SELECT * FROM products LIMIT 10"); $stmt->execute(); $products = $stmt->get_result(); $produc ...

Executing callback functions after numerous asynchronous calls have been completed

Is there a method to delay the execution of a specific line of code until multiple API calls have all returned? Typically, I follow this pattern: APIService.call(parameter).then(function(response) { // Do something callBack(); }); This approach wo ...

Retrieving the Chosen Item from Kendo Dropdown Menu

Currently utilizing the Kendo Drop Down List with Kendo Angular directives. My markup looks like this: <input id='myDropDownList' kendo-drop-down-list ng-model="selectedSport" k-data-source="sports" k-data-text-field="'name'" /> ...

Utilizing Nuxt3's auto-import feature alongside Eslint

I'm having trouble finding an eslint setup that is compatible with Nuxt3's auto-import feature to prevent no-undef errors. I have tried various packages like @antfu/eslint-config, plugin:nuxt/recommended, @nuxt/eslint-config, @nuxtjs/eslint-confi ...

The filtering feature for array and model selection in Angular's UI-Select appears to be malfunctioning

Below is a Json structure: $scope.people = [ { name: 'Niraj'}, { name: 'Shivam'}, { name: 'Arun'}, { name: 'Mohit'}] There's also a variable, var array = "Niraj,Shivam";. My goal is to filter out the names fro ...

Which should I use - Angular directive or CSS selector, for better performance?

Currently expanding my knowledge on angular and exploring the capabilities of the ngClass directive. I have come across this interesting functionality: <li ng-repeat="language in languages" ng-class="{line:$even}">{{language}}</li> Alternativ ...

How can you calculate the number of elements in a jQuery array and iterate through each of them?

After extracting a string from a mySQL query with PHP, my AJAX script comes into play. This string is then dissected and placed into a jQuery array. The results are displayed on the screen using .html() The length of this array can range from zero items t ...

Error: Uncaught TypeError - Unable to assign a value to the 'status' property

Hello everyone, I am currently facing an issue with validating the response from my server using Axios in VueJS. axios.post('/login', { email: this.email, password: this.password }).then(response => { if (response.status == 200) { $ ...

When a menu item is clicked, apply a class and change the display property to

I currently have an HTML menu with a submenu structured as follows: <li id="item-3" class="menu-item has-children-3"> <a href="#" class="sf-with-ul"><span>Auto</span></a ...

There seems to be an issue when trying to retrieve data from a JSON array stored

I have a SQL table with a column that stores JSON arrays. I am able to retrieve the data using Node.js, but when I try to manipulate the JSON array, I encounter errors consistently. Here is an example of my JSON array in the SQL database: { characters: [{ ...

Calculate the worth of a specific item within an array of objects and save the outcome as a new attribute

I am attempting to calculate the value in each element and then create a new element called "Count". Rule: Count the quantity if the next element has the same "Quantity" value, then add the total to a new element named "Count". I have tried implementing th ...

A guide to generating a user-specific log file in ASP.NET by leveraging session data and log4net

I have recently set up logging using log4net and successfully created a log file to store information. However, I am now faced with the task of implementing user profiles and generating log files based on the user with a specific format [AID_YYYYMMDD]. C ...

"Optimizing App Pool Performance with IIS Precache Event Monitoring

Our asp.net LOB web application is quite large. The issue we are facing is the delay of up to 10 seconds when the app pool is started or recycled, making the first page load slow. This results in users seeing a white page with a loading spinner until IIS ...

What is the best way to include an ajax request within a function and execute it only when needed?

I am working on an ajax request that fetches data from a specific URL. I have the following code snippet: $.ajax({ type: 'POST', url: '/get-result.php', dataType: 'json', data: 'pid=' + $(this).attr( ...

Generate and save a document

Upon clicking the button, I am trying to generate a CSV file and download it right away. My current approach is as follows: html: <a class="btn btn-primary" @click="downloadCsv">Download CSV</a> <a v-if="fileObjectUrl !== null" ref="down ...

What is the best way to retrieve and display the heading of the current section that is being viewed using Bootstrap Vue's ScrollSpy feature?

I am currently using the Bootstrap Vue Scrollspy feature in my project with Nuxt js. The elements are correctly referenced and are successfully spying on the content. What I would like to achieve is having the ability to update a specific div with the curr ...

The most recent version of Angular featuring the powerful Angular-anim

Currently, I am in the process of revamping an application that was initially developed using a combination of jquery, bootstrap, and kendo ui. Moving forward, the application will transition to an angular (2/4) and kendo framework. In the previous setup, ...