Incorporate AngularJS {{expression}} into ng-repeat by utilizing a separate array

After completely rebuilding my website (which was originally hacked together with Wordpress), I decided to utilize Laravel and AngularJS. The transition has been quite challenging, but I'm almost there, except for one issue.

On my website, I have 'schemes' (or courses) that consist of 'units', which in turn contain 'lessons'. Retrieving this data using Eloquent has been smooth, and I am able to retrieve valid JSON in the following example structure...

[
{
    "id": "1", 
    "title": "Sports",
    "description": "This is a Sports course!",
    "units": [
        {
            "id": "1",
            "title": "Tennis",
            "lessons": [
                {
                    "id": "6",
                    "title": "Serving"
                },
                {
                    "id": "7",
                    "title": "Hitting the ball with top-spin"
                }
            ]
        },
        {
            "id": "2",
            "title": "Athletics",
            "lessons": [
                {
                    "id": "1",
                    "title": "Long Jump"
                },
                {
                    "id": "2",
                    "title": "Hurdling Technique"
                }
            ]
        },
        {
            "id": "4",
            "title": "Golf",
            "lessons": [
                {
                    "id": "4",
                    "title": "Pitching"
                },
                {
                    "id": "5",
                    "title": "Putting"
                }
            ]
        }
    ]
}
....
]

Additionally, I have a simple array that contains completed lesson ids for a specific user...

[2, 6, 8, 9] 

Within my view, I am using nested ng-repeat loops as shown below...

...
<div ng-controller="SchemesController">
<div ng-repeat="scheme in schemes">
    <h1>{{scheme.title}}</h1>
    <div ng-repeat="unit in scheme.units">
        <h3>{{unit.title}}</h3>
        <div ng-repeat="lesson in unit.lessons">
            <div>{{lesson.title}}: {{status}}</div>
        </div>
    </div>
</div>
</div><!--[end of ng-controller="SchemesController"]-->
....

The SchemesController is quite simple and looks like this...

   var app = angular.module('schemesApp', []);

   app.controller('SchemesController', function($scope){
    $scope.schemes=jsonData;
   });

The challenge I'm facing is populating the {{status}} field to indicate 'Complete' or 'Incomplete'. I have tried modifying the original array but didn't make much progress. I even explored using underscore.js but still couldn't figure it out.

Is there a way to achieve this, possibly by using underscore.js or by creating and calling a JavaScript function?

Any assistance or guidance on this matter would be greatly appreciated. As a school teacher, I find programming and web design to be a fun use of my spare time, so I apologize if my question seems trivial. Thank you in advance!

By the way, if anyone has a better 'title' suggestion for this question, please feel free to share.

Answer №1

Assuming there is no need to persist the status back to the database...

The issue lies here:

<div>{{lesson.title}}: {{status}}</div>

It's unnecessary to store the status in the data model since it's only used for display purposes.

Imagine your array of completed lessons is set up like this:

$scope.completedLessons = [1, 2, 3, 4, 5] // Or however you'd assign it

You should create a function in your scope like this:

$scope.isLessonCompleted = function(lessonId) {
  return $scope.completedLessons.indexOf(lessonId) > -1;
};

Then update the html as follows:

<div>{{lesson.title}}: {{isLessonCompleted(lesson.id) && 'Complete' || 'Incomplete'}}</div>

Answer №2

In the scenario where lessons also function as a model and each lesson requires a status, which is not a predefined column in your database table but is a value you need to determine programmatically, you can create a custom model accessor. To do this, simply insert the following code snippet into your models/Lesson.php:

// Include custom accessor attributes
protected $appends = ['status'];

public function getStatusAttribute() {
    // Implement your logic here
    return 'Complete';
}

By utilizing this approach, the Eloquent ORM will retrieve the data along with the added status attribute within the object. Consequently, you can easily access it using $lesson->status in PHP or lesson.status in JavaScript.

To delve deeper into this topic, refer to the official Laravel documentation on accessors and mutators

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

Combine an array of objects that are dynamically created into a single object

Having trouble transforming the JSON below into the desired JSON format using JavaScript. Current JSON: { "furniture": { "matter": [ { "matter1": "Matter 1 value" }, { "matter2": "Matter 2 value" }, { ...

Looking to create an anchor tag that navigates to a specific ID on the page while accommodating a fixed header placement

In my application, the homepage's carousel displays multiple images with dynamically generated anchor tags that link to different routes. When clicking on the anchor tag, the page scrolls to the linked image but is obstructed by a fixed header. I want ...

Laravel's Eloquent connection displaying a null output

I'm facing some challenges with my Eloquent relationships as I work with a couple of tables for demonstration purposes Schema::create('properties', function (Blueprint $table) { $table->integer('id')->unsigned()->index ...

Creating intricate HTML components using jQuery/Javascript

My current challenge involves receiving data from JSON and dynamically displaying it on a web page within complex HTML structures, such as tables with lists. Every time new JSON data is received, I need my HTML elements to be dynamically regenerated. For ...

Retrieve a string value in Next.JS without using quotation marks

Using .send rather than .json solved the problem, thank you I have an API in next.js and I need a response without Quote Marks. Currently, the response in the browser includes "value", but I only want value. This is my current endpoint: export ...

Making changes to a variable or option through the props in a different file

In the index.js file, I have implemented getStaticProps() to fetch data from an exported function. This function requires 2 parameters, one for the type of listing and the quantity. export async function getStaticProps() { const type = 0 const data = a ...

Can you explain the mechanics behind Google Voice Search? And is there an available API for it?

Is this the right place to ask how the voice-activated search feature on Google's homepage functions? I'm curious about whether it utilizes Flash, a plugin integrated into Google Chrome, or some other method to access the microphone. The idea of ...

Encountered a problem during the installation of tensorflowjs for node | Received an error: Command failed: node-pre-gyp install

While attempting to install @tensorflow/tfjs-node, I encountered the following error: Command failed: node-pre-gyp install --fallback-to-build. Is there a solution to resolve this issue? Below is the complete log: npm ERR! code 1 npm ERR! path E:\ ...

Encountering an issue when attempting to host a Next.js application on Vercel

Why is it important to regularly do this task as per the instructions provided in the link? Info - Working on creating a highly efficient production build... Note: Next.js now collects completely anonymous telemetry data on user usage. This data helps sha ...

Is it feasible to maintain a variable as a reference across views while utilizing ng-view?

I am facing a unique challenge: I have a webpage with two tabs that need to utilize ng-view from AngularJS. The twist is that both tabs must share the same variable, similar to referencing a variable in C# using the "ref" keyword. If you want to see an ex ...

Create a shader in ThreeJS without the need to include a Geometry in the scene

Currently, I am experimenting with drawing shapes or geometric figures in ThreeJS r128 using only shaders. The traditional approach in this library involves creating a mesh with a geometry associated with it, and then applying a shader using the ShaderMat ...

Navigating with Express to display HTML using JSON information

Here's the issue I'm facing: I have a Nodejs server running with a mongoDB. Currently, I've been sending query results as JSON data to the browser. app.get('/gesamtergebnis', function(req,res){ User.aggregate([{$group: { ...

Searching for values within a JSON array in Postgresql using wildcard characters and comparison operators, while taking advantage of indexing

I am working with a table containing JSON array data that I need to search through. CREATE TABLE info (id SERIAL, content JSON); INSERT INTO info (id, content) VALUES (1, '[{"name": "Info A", "value": 10}]'); INSERT INTO info (id, content) ...

What advantages does using extend in the prototype offer in the inheritance pattern of three.js?

While delving into the world of Three.js framework and in search of an efficient JavaScript inheritance pattern, I decided to explore how it was implemented in Three.js itself. After studying it closely, I have gained a solid understanding of most aspects, ...

basic fading javascript image rotator

While looking for a simple fade image rotator, I stumbled upon this old post: Simple fade javascript image rotator request I finally found what I was searching for: $(function() { $('#fader img:not(:first)').hide(); $('#fader img').c ...

Tips for implementing X-XSS-Protection: 1; mode=block in HTML

I'm struggling with where to place this piece of code in my existing code. Should it be added to the header section? <head> <meta content="text/html; charset=UTF-8; X-Content-Type-Options=nosniff" http-equiv="Content-Type" /> <title> ...

Angular's onreadystatechange event is triggered when the state

Hey there, I'm new to Angular and had a question. Is it possible to use the $http service in Angular to trigger a function whenever there is any change in the ready state/status, not just for success or failure? If so, what would be the equivalent ang ...

What is the best way to send an array to the server with $http in AngularJS?

I have a collection of unique identifiers that I need to send to the server. Most online solutions suggest passing these identifiers as query parameters in the URL, but this approach is not ideal for me as there could be a large number of identifiers invol ...

The functionality of ngSubmit and ngDisabled seems to be malfunctioning, although ngModel is successfully linked to the

Despite following the usual process of creating a form in AngularJS, the ngSubmit function is not working as expected and the ngDisabled feature is failing to disable the button when the fields are empty. I even tried isolating the section in a new project ...

Tips for hiding a soft keyboard with jQuery

Here is a text button: <input type="text" class="field" id="something" name="something" placeholder="text" autofocus /> I want to prevent the android soft keyboard from popping up and keep the focus on this field. I only want to do this for this ...