Combine object attributes to create a new column in a table

Check out this plunker I created. What is the most efficient way to merge the contents of $scope.blacklist into $scope.friends when

ng-click="showColumn('Blacklist');"
is triggered, and also add a new column named Coming to the table.

Ng-App & Ng-Controller

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

myApp.controller('MainCtrl', ['$scope', MainCtrl]);

function MainCtrl($scope, $http) {

    $scope.friends = [{name:'John', phone:'555-1276'},
                      {name:'Mary', phone:'800-BIG-MARY'},
                      {name:'Mike', phone:'555-4321'},
                      {name:'Adam', phone:'555-5678'},
                      {name:'Julie', phone:'555-8765'}];

    $scope.coming = [{coming: 'x'},
                      {coming: 'x'},
                      {coming: 'x'},
                      {coming: 'x'},
                      {coming: 'x'}];

    $scope.showColumn = function (type) {
      if (type === 'coming') {
        // INSERT Code here
        console.log('Try add column coming');
      }
    } 

    $scope.getFilter = function () {
        return $scope.filter;
    };  

    $scope.setFilter = function (filter) {
        $scope.filter = filter;
    }; 
}

View

<div ng-app="myApp">
      <div ng-controller="MainCtrl">
        <hr />
        <a ng-click="showColumn('coming');">Show "coming"</a>
        <hr />
        <table class="table">
          <tbody> 
            <tr>
              <th>Name</th>
              <th>Phone</th>
            </tr>
            <tr ng-repeat="friend in friends | filter:getFilter()">
              <td>{{friend.name}}</td>
              <td>{{friend.phone}}</td>
              <td ng-repeat="come in coming">{{come.coming}}</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

Answer №1

Attempt

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

myApp.controller('MainCtrl', ['$scope', MainCtrl]);

function MainCtrl($scope, $http) {

  $scope.friends = [{
    name: 'John',
    phone: '555-1276'
  }, {
    name: 'Mary',
    phone: '800-BIG-MARY'
  }, {
    name: 'Mike',
    phone: '555-4321'
  }, {
    name: 'Adam',
    phone: '555-5678'
  }, {
    name: 'Julie',
    phone: '555-8765'
  }];

  $scope.coming = [{
    coming: 'x'
  }, {
    coming: 'x'
  }, {
    coming: 'x'
  }, {
    coming: 'x'
  }, {
    coming: 'x'
  }];

  $scope.showColumn = function(type) {
    if (type === 'coming') {
      $scope.showComing = true;
      angular.forEach($scope.friends, function(obj, i) {
        obj.coming = ($scope.coming[i] || {}).coming;
      })
    }
  }

  $scope.getFilter = function() {
    return $scope.filter;
  };

  $scope.setFilter = function(filter) {
    $scope.filter = filter;
  };
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
  <div ng-controller="MainCtrl">
    <hr />
    <a ng-click="showColumn('coming');">Display "coming"</a>
    <hr />
    <table class="table">
      <tbody> 
        <tr>
          <th>Name</th>
          <th>Phone</th>
          <th ng-show="showComing">Coming</th>
        </tr>
        <tr ng-repeat="friend in friends | filter:getFilter()">
          <td>{{friend.name}}</td>
          <td>{{friend.phone}}</td>
          <td ng-show="showComing">{{friend.coming}}</td>
        </tr>
      </tbody>
    </table>
  </div>
</div>

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

Ajax sends the URL location to Python

I'm attempting to piece together some code. There are two distinct functions that I am trying to merge into a single entity. Code snippet: <!DOCTYPE html> <head> <meta http-equiv="content-type" content="text/html;charset=UTF-8"> &l ...

Encountering unexpected behavior with the .data() method

I'm encountering an issue with my code <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv= ...

Tips for implementing validation in AngularJS

Could someone help me with AngularJS validation? I'm new to it and trying to make sure everything is correct. var app=angular.module('myApp',[]) app.controller('myController',function($scope){ $scope.clickMe = function(){ if($(& ...

Angular 11 along with RxJS does not support the combineLatest method in the specified type

Hey there, I'm currently working on utilizing the combineLatest operator to merge two streams in Angular, but I keep encountering an error message stating that "combineLatest does not exist on type". I've attempted to move the code into a .pipe() ...

Tips for utilizing the jQuery selectbox plugin on multiple elements within a single page

On my webpage, there are 3 select boxes that I want to customize using a jQuery selectbox plugin. However, the issue I'm encountering is that the plugin only works on the first select box and the others remain unchanged. Does anyone know why this mig ...

Why isn't the unit test passing when it clearly should be?

I am encountering an issue with testing a simple function that I have created. Despite the fact that the function works correctly in practice, it is not being tested properly... Explanation of how my function operates (While it functions as intended, the ...

What is the method for utilizing tsx within the Vue Composition setup function?

As I write tsx in @vue/composition-api setup() function, like so: <script lang="tsx"> import { defineComponent,} from '@vue/composition-api'; export defineComponent({ setup() { const foo = { bar: 1 baz: render() ...

Troubleshooting a bug in React TypeScript with conditional logic

I have a new message button and a few conversations. When I click on a conversation, the right side should display the message box. Clicking on the new message button should show the create new message box. Here are my useState and handlers: const [newMess ...

Tips for aligning two separate texts depending on if they appear on the same line or not

Looking to align text B to the right when text A and B are on the same line, but automatically aligning text B to the left if it wraps to the next line due to space constraints. .text-left { float: left; /* Float to the left */ } .text-right { fl ...

What is the best way to execute fetch calls in sequence (A -> B -> C) within a React component?

I'm facing an issue with three fetch functions - a(), b(a_id), and c(b_id). The flow is such that function a returns an a_id which is then passed to function b, and b in turn returns an id passed to function c. componentDidUpdate(prevProps) { this ...

Enhance the appearance of your custom Component in React Native by applying styles to Styled Components

I have a JavaScript file named button.js: import React from "react"; import styled from "styled-components"; const StyledButton = styled.TouchableOpacity` border: 1px solid #fff; border-radius: 10px; padding-horizontal: 10px; padding-vertical: 5p ...

Unable to extract text input from form

When designing a form for users to change their password, I encountered an issue where passing 3 empty Strings instead of a User object resulted in the Strings being returned as empty when submitting the form. Is there a way to retrieve String values from ...

AngularJS routing fails to function when viewing past actions

Currently, I am working on coding an Angular application and have completed setting up my app routing as shown below: AdminDashboard.config(['$routeProvider','$locationProvider',function($routeProvider, $locationProvider){ $rou ...

A different component experiences an issue where Angular Promise is returning undefined

This is the carComponent.ts file containing the following method: async Download() { try { const settings = { kit: true, tyres: true, serviced: false, }; const [kits, tyres] = await Promise.all([ this.c ...

Exploring ways to personalize the behavior and style of the material-ui Accordion component

There is a div container in gray with an accordion component containing only one AccordionSummary component. Below that is another div in blue. The initial view looks good (see pic #1). When the accordion is expanded: The AccordionDetails component is dis ...

Associate text with a color from a predetermined list (JavaScript)

As I work on adding tags to my website for blog posts, I have a specific vision in mind. Each tag should be assigned a unique background color selected from a predefined array of theme colors. My goal is to assign the same background color to tags with id ...

"Put Phonegap on hold for a bit and disable landscape mode

I am currently using Phonegap to develop an Android game. My project includes a lobby feature where players can search for opponents and engage in chat with other players. Once a player has found their opponent, they can commence playing the game together ...

Tips for extracting data from arrays with multiple dimensions - (JavaScript)

I am looking to extract string values from a multi-dimensional array and store them in a new array as the answer. For Example : var dimStr = [ "First-one", ["Double-one", "Double-two", "Double-three", ["Triple-one", "Triple-two"] ], "First-two" ] ; The ...

Show a visual content in Grails Server Pages created through a specific class

In my class file, I have the image path displayed as shown below: String val; val+= "<img src=/"PATH_TO_FILE/" alt=/"sometext/">" Now, I am attempting to load the image in a gsp view within a div using jQuery from the val variable. The image is be ...

Creating CSS animation for the most recent element that has been dynamically inserted using JavaScript and Vue.js

After adding a new div with Vue, I noticed that the opacity effect is being applied to the previous element instead of the newly added one. I want the effect to always appear on the latest element added at index 0. What could be causing this issue? Here i ...