Is there a way to enable 2-way binding when using ng-repeat and foreach together?

Although I've made progress in learning angularjs with routes, views, and ui-bootstrap, I'm facing challenges when working with scope data and two-way binding. While using ng-repeat, I discovered the ability to bind the loop to a foreach in the controller for additional processing, which led me to try combining the two functionalities.

In my pursuit to understand scope in angularjs ng-repeat, I found myself dealing with a list of persons, each possessing a weekSchedule object used to create a table representing schedule information for a week.

The process involves looping through the list of persons (outer loop) and then iterating over an array numbered 1 - 7 (inner loop). The objective is to match up the 'day of the week' number from the schedule data with the day number and populate the schedule times accordingly, or leave it blank if there's no match. I need the weekSchedule data for each person to be within scope during the inner loop iteration for this to work effectively.

Despite reading various resources on this issue, I haven't been able to find a suitable solution. I've attempted numerous strategies including using rootScope, $parent, broadcast, setters & getters, setting the person first before executing the inner loop code via a function, among others.

At one point, I tried setting the weekScedule in scope with ng-init & ng-model within my table. Additionally, I experimented with a 'child scope ng-init with 'day.weekSchedule=person.weekSchedule'. Although these methods somewhat placed the object into scope in the View template, only the last object was displayed correctly. Consequently, the object in the first outer iteration had the wrong association.

<table width="100%" border="1">
    <tr ng-repeat="person in scheduleData">
        <th ng-init="setWeekSchedule(person.weekSchedule)">{{person.name}}</th>
        <td width="12%" ng-repeat="day in dayNumbers">
            <span ng-init="day.weekSchedule=person.weekSchedule"></span>
            day.id: {{day.id}}<br />
            1st schedule id: {{day.weekSchedule[0].id}}
        </td>

    </tr>
</table>


$scope.dayNumbers = [{id:1},{id:2},{id:3},{id:4},{id:5},{id:6},{id:7}];

$rootScope.person = {
    weekSchedule: [{ id: 0 }]
};

$rootScope.setWeekSchedule = function(weekSchedule) {    
    $rootScope.person.weekSchedule = weekSchedule;
};

$scope.dayNumbers.forEach(function(day){
    day.weekSchedule = $rootScope.person.weekSchedule;
    console.log('day.id: ' + day.id);
    console.log('1st schedule id: ' + day.weekSchedule[0].id);
});

$scope.scheduleData = [
    {"id":"1","name":"Jim","weekSchedule":[
    {"id":"1001","dow":"1","scheduleDate":"01/08/2016"},
    {"id":"1002","dow":"2","scheduleDate":"01/09/2016"},
    {"id":"1003","dow":"4","scheduleDate":"01/11/2016"},
    {"id":"1004","dow":"5","scheduleDate":"01/12/2016"}]},
    {"id":"1","name":"Kim","weekSchedule":[
    {"id":"1005","dow":"2","scheduleDate":"01/09/2016"},
    {"id":"1006","dow":"3","scheduleDate":"01/10/2016"},
    {"id":"1007","dow":"5","scheduleDate":"01/12/2016"},
    {"id":"1008","dow":"6","scheduleDate":"01/13/2016"}]}
];

https://i.sstatic.net/lgm4C.png

Regardless of how I configure the schedule in the controller, accessing it correctly in the View iterations remains an issue. And no matter how I set up the schedule in the View, processing it accurately in the Controller continues to pose a challenge.

Answer №1

Develop a custom function to create a reference table.

$scope.crossReference = function(schedule) {
    var referenceTable = {};
    angular.forEach(schedule, function(entry) {
        referenceTable[entry.dow] = entry;
    });
    return referenceTable;
};

Integrate this function into your template.

<td width="12%" ng-repeat="day in dayNumbers">
    Day ID: {{day.id}}<br />
    1st schedule ID: {{crossReference(person.weekSchedule)[day.id].id}}
</td>

Check out the live demonstration on JSFiddle.

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

JavaScript Array Multiplication Theory

I am working with 2 arrays list1 = ["x","y"] list2 = [ ["5","6","7"],["20","21","22"]] My goal is to create an array of objects like this: [ {list1: x , list2: 5}, {list1: x , list2: 6}, {list1: x , list2: 7}, {list1: y , list2: 20}, {list1: y , l ...

Chess.js TypeScript declaration file for easy implementation

Currently, I am delving into learning typescript and have taken up the challenge of crafting a declaration file for the chess.js library. However, it seems that I am struggling to grasp the concept of creating one. Whenever I attempt to import the library ...

When attempting to delete, I encounter an error stating that $index is undefined

I am currently working on a project that involves Angular and PHP. I have encountered an issue while trying to delete some information, even though the function seems to be retrieving the data correctly. I'm puzzled as to why it is not working as expe ...

What is the meaning of a word character in a character class?

\w - represents the character class [A-Za-z0-9_] Character class Despite this, I find it difficult to grasp how it is interpreted within a character class. When I use [\w-~] let test = (str) => /^[\w-~]+$/.test(str) console.log(tes ...

The problem of "undefined function appendTo" is causing issues

My jQuery code looks like this: $(function() { var productTextTemplate = $('#product-text-template').html(); var productTemplate = $('product-template').html(); var product = productTextTemplate.appendTo(productTemplate); a ...

The modal appears on the screen prior to the content being shown

While attempting to render a bootstrap modal with content from a REST call, I am encountering an issue where the modal appears before the content has finished populating. The modal is triggered by a button click event. If I click the button again after wa ...

A guide on updating a MySQL table using a JSON object in Node.js

I have a JSON Object and need to UPDATE a mySQL table without listing all of the keys individually For an INSERT operation, I use the following code: var arrayValue = Object.keys(obj).map(function(key) { return String("'"+obj[key]+"'"); ...

Leverage the basename feature in React Router when rendering on the server side

My website is being hosted from the directory /clientpanel on my server, making the URL http://xxx.yy/clientpanel. The client-side code looks like this: const history = useRouterHistory(createHistory)({ basename: "/clientpanel" }); render( <Ro ...

Synchronizing multiple file changes simultaneously in Node.js

I have a small development server set up specifically for writing missing translations into files. app.post('/locales/add/:language/:namespace', async (req, res) => { const { language, namespace } = req.params // Utilizing fs.promises l ...

What is the best way to insert an object at a particular position within an array containing numerous nested objects?

This is the given Object: [ { "id": "1709408412689", "name": "WB1", "children": [ { "id": "1709408412690", "n ...

Error: Please provide the required client_id when setting up Google Sign-In with Next-Auth

I have been trying to implement the Sign in with Google option in my Next.js application using next-auth. Below is a snippet of my [...nextauth].js file located in the api/auth folder: import NextAuth from "next-auth"; import Google ...

Receive the deleted entry upon clicking the thead | Error发

Is there a way to permanently delete a row in a datatable? If I delete all the rows, I would like the datatable to display the default message of "No data available". I have attempted some POST requests : But with no success. DataTables remove row butto ...

Employ the AngularJS Variable only when its ID aligns with another AngularJS Variable

How can I display an image in my ng-repeat statement based on matching IDs? The goal is to show the image where the ng-repeat's ID matches the image object's ID. I am struggling with implementing this feature, here is a pseudo code example of wh ...

Stopping CSS animations at a specific point along the path without using timing functions can be achieved by implementing a targeted

Is there a way to pause an animation at the 50% mark for 2 seconds and then resume? P.S. The setInterval method is not recommended! function pauseAnimation() { document.getElementById("0").style.animationPlayState = "paused"; }; var pauseInterval = set ...

Initializing collapsed state in AngularJS Bootstrap

Reviewing the code provided: <div class="pull-right text-success m-t-sm"> <button class="btn btn-default" ng-init="isCollapsed = false" ng-click="isCollapsed = !isCollapsed" data-toggle="tooltip" data-placement="top" title="" data-original-ti ...

Signal for a complete 360 degree rotation of an image

Looking to enhance my 360 image rotator with an indicator that fades out after the first image. I added this function to the end of my 360.js: (function(){ if( $('#first').css('visibility','hidden')) { $('#rotat ...

Can you point me towards the location of Sigma.js' sigma.utils.xhr() function?

I came across a peculiar issue with lines 23 and 24 of sigma/plugins/sigma.neo4j.cypher/sigma.neo4j.cypher.js: sigma.neo4j.send = function(neo4j, endpoint, method, data, callback) { var xhr = sigma.utils.xhr(), Surprisingly, sigma/src/utils/sigma.uti ...

How can I pass a PHP variable to a JavaScript variable using PHP and JQuery/JavaScript?

I am facing a challenge with a large <select> input that is used across multiple pages. My idea is to separate this dropdown box into its own PHP file and load it externally using JQuery. Is this approach feasible? Here's an outline of what I ha ...

Angular2 - How to track or listen for (click) events on dynamically inserted HTML elements

I'm trying to inject a string with a dynamically retrieved (click) event into an Angular2 template. Since this string is fetched from the back-end after the DOM is loaded, Angular doesn't recognize the injected event. Here's an example of t ...

What is the best way to rearrange elements within an object when there is no predetermined starting order?

Someone assisted me in refining this code snippet import React, { useEffect, useState } from "react"; import _ from "lodash"; // const SeleccionClientes = ""; const items = [ { client: "Microsoft", idClient: 0, idProjectType: 1, project ...