Combine two pieces of data from a JSON object using Angular's ng-repeat

Trying to organize data from a separate array into one section of a table. The first JSON named "names" :

[
        {
            "name": "AAAAAA",
            "down": "False"

        },

        {
            "name": "BBBBBB",
            "down": "True"
        },
        {
            "name": "CCCCC",
            "down": "False"
        }
]

Second JSON named "data" :

[
         {
            "data": "35%"
        }
]

Javascript:

 var app = angular.module('app', []);
    app.service('service', function($http, $q){
        this.getNames = function () {
            var names = $http.get('names.json', {cache: false});
            var datas = $http.get('data.json', {cache: false});
            return $q.all({datas,names});
        };

        });
    app.controller('FirstCtrl', function($scope, service, $http) {
            var promise = service.getNames();
            promise.then(function (data) {
                $scope.names = data.names.data;
                $scope.datas = data.datas.data;
                $scope.namesanddata = $scope.names.concat($scope.datas);

                console.log($scope.namesplit);
                console.log($scope.datas);

            });
    });

Table in HTML :

div ng-controller="FirstCtrl"
     <table>
        <tbody>
          <tr ng-repeat="name in namesanddata">
            <td>{{name.name}}</td>
             <td ng-if="name.down=== 'False'">{{name.down}}</td>
             <td ng-if="name.down !== 'False'">{{name.data}}</td>
          </tr>
        </tbody>
      </table>
    </div>

Issue -

<td ng-if="name.down !== 'False'">{{name.data}}</td>
does not display in the table. When logged in console, it concatenates into an array with 4 objects and potentially doesn't appear next to {{name.name}} in the table. Unsure of how to display {{name.data}} from another JSON file in the table instead of {{name.down}}. Thank you for any assistance provided.

Answer №1

Here is the desired output:

AAAAAA  False
BBBBBB  35%
CCCCC   False

Please make sure to delete this line from the Controller:

$scope.namesanddata = $scope.names.concat($scope.datas);

Next step:

Option 1 - Update the view directly

Modify your ng-repeat like so:

<tr ng-repeat="name in names">
    <td>{{ name.name }}</td>
    <td>{{ (name.down === 'False') ? name.down : datas[0].data }}</td>
</tr>

OR

Option 2 - Use a Filter to keep the view clean

app.filter('myFilter', function () {
    return function(items, datas) {
        var filtered = [];
        angular.forEach(items, function (i) {
            if (i.down !== "False")
                i.down = datas[0].data;
            filtered.push(i);
        });
        return filtered;
    }
});

Update your ng-repeat as shown below:

<tr ng-repeat="name in names | myFilter: datas">
    <td>{{ name.name }}</td>
    <td>{{ name.down }}</td>
</tr>

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

Guide to saving output to a file using node.js and express

I have developed an application using node.js and express.js on top of elasticsearch. The application is quite simple, featuring a search box that returns results in JSON format when querying for a specific keyword. For example, searching for the word "whi ...

MEAN stack does not support the AngularJS module 'ngCookies'

I have been researching similar issues related to the order of loading Angular and angular-cookies, but in my case, it is different. I am currently following a tutorial on building an AngularCMS using the MEAN stack (you can find it at Building a CMS in th ...

The conflict arises when importing between baseUrl and node_modules

I am currently working on a TypeScript project with a specific configuration setup. The partial contents of my tsconfig.json file are as follows: { "compilerOptions": { "module": "commonjs", "baseUrl": &quo ...

Selecting the appropriate technology or library for incorporating user-defined text along a designated path within established areas

I am currently developing an admin dashboard with CodeIgniter 2 that allows the admin to upload custom images, particularly ones with blank spaces for text overlay. The goal is to enable regular users to add their desired text in specific areas defined by ...

Which one to use: Response JSON object or JSON.stringify()?

If I have JSON content that I want to return, what is the best way to do it? let data = { x: 'apple', y: 'banana' }; Is it better to: A) Return the object as is when sending the response with res.send(data)? B) Convert the objec ...

Mocking Ext.Ajax.request in ExtJS 4.2.1 is a process of em

When it comes to frontend unit testing using Jasmine, one of the challenges I faced was mocking all the requests in my application. Luckily, I have already tackled a method to mock all my proxies successfully: proxy: appname.classes.proxy.ProxyNegotiator ...

How to Filter Fields in AngularJS Based on a Start Date and End Date?

Hey everyone, I'm trying to filter items based on the start and end dates using the daterange functionality in my meanjs app. I've tried multiple approaches but haven't found a solution yet. If anyone knows how to do this, please help me out ...

Storing a single array from a nested array into the state of a React component

As a new enthusiast in the world of React, I could really use some guidance. Currently, I have an array stored in a state variable called projects 0:{id: 1, title: "Business Web", category: "Web Design", deleted_at: "0000-00-00 00:00:00"} 1:{id: 2, title ...

Textbox value disappears after being updated

When I click on the edit link (name), the value from the database is displayed as a textbox. However, when I update another normal textbox (age), the value in the edit link textbox disappears. Strangely, if I input a new value into the edit link textbox, i ...

Extracting an ID value from a select box in Vue.js

I'm attempting to extract the value of idTipoExame from the following JSON: { "idTipoExame": "11", "mnemonico": "AUR", "exame": "ACIDO URICO" }, { "idTipoExame": "24&qu ...

Is there a way to delete a field from a JSON object using JavaScript?

Searching for a way in Node.js to eliminate the date and operation fields from the database. Any suggestions on how to do this? Currently, all fields are being transferred to the FE. The collection pertains to MongoDB. collection.find({'recordType&ap ...

Effective strategies for minimizing the bundle size of your NextJs application

Recently, I launched my first NextJS app and was surprised to see that the initial bundle size is around 1.5Mb, which seems quite large for me as a beginner in using Nextjs. I have shared an image of the yarn build and also my package.json. All the pages ...

Best Method for Updating a Single Scope and Setting the Others to False in AngularJS

If I have 4 fields in my view that need to be toggled open or closed when clicked, with the requirement of closing the other three, how can this be achieved without duplicate code? <div class="square red"></div> <div class="square blue"> ...

Tips for showcasing elements individually in JavaScript when a button is clicked and halting on a random element

I have some names stored in h3 tags. I want to highlight one name at a time when I click a button, stopping at a random name. <div class="all-names"> <h3 class="name-one"><span class="line">Name ...

What is the default method for automatically disabling drop down fields?

I've created a script that will gray out a drop-down field if a prior selection wasn't made. Once the appropriate choice is selected, the grayed-out field will become active. My query is, how can I set the drop-down field to be initially grayed ...

Tips for arranging JSON structures within an array

While I have experience working with JSON structs and successfully integrating them with other APIs in the past, I am encountering a challenge with this particular API's JSON data. It appears that the data is wrapped within an array labeled 'List ...

Tips for displaying dynamic content based on conditions in React

I am currently working on adjusting the boilerplate repository in order to render different pages based on whether a user is logged in or not. The current setup always displays the same page but includes additional content if there is an authenticated user ...

Array buffers are scheduled by BinaryJs and the Audio API

My node.js server is streaming some ArrayBuffers: var BinaryServer = require('binaryjs').BinaryServer; var fs = require('fs'); var server = BinaryServer({port: 2000}); server.on('connection', function(client){ var file = f ...

The operation to assign a value to property 'two' cannot be completed as it is currently undefined

I'm facing an issue with the code below and cannot figure out why I am encountering the error message. I have ensured that each object contains a value, so why is there a reference to 'undefined'? Cannot set property 'two' of unde ...

Express.js router defining a module issue

I have encountered a problem while working on my Express.js project. The 'slug' variable that I defined in app.js is not being recognized in the controllers within the router. Is there a way to define these variables in a central location, as I w ...