Directive in Angular for customer management with filtering and sorting functionality

I am struggling to organize the JSON object by userType using ng-repeat. While I have successfully retrieved and displayed the data, my ISSUE is that I need to sort and display two different tables for the following list: One for MARRIED individuals and another for SINGLE individuals.

Any suggestions or help on how to sort married/single when using ng-repeat and displaying them in TWO tables would be greatly appreciated....

.controller('userInfo', ['$scope', 'userService', function ($scope, userService) {
      userService.getuserList().then(function (users) {
        users = [
                {
                    "personalInfo": {
                        "firstName": "Richardoo",
                        "lastName": "Gil",
                        "maritalStatus": "Married",                    
                        "percentage": "50"
         }},
         {
                    "personalInfo": {
                        "firstName": "Richardoo",
                        "lastName": "Gil",
                        "maritalStatus": "Single",                    
                        "percentage": "50"
          },
          {
                    "personalInfo": {
                        "firstName": "Richardoo",
                        "lastName": "Gil",
                        "maritalStatus": "Married",                    
                        "percentage": "50"
          }
         ]

        $scope.users = users;
      });
    }])

.directive('userDetails', function () {
      return {
        restrict: 'E',
        scope: {
          users: '='
        },
        controller: function ($scope) {
          $scope.showEdit = function () {
            $scope.isEdit = true;
          }
        },
        template: `<div class="table-responsive">
      <table class="table">
          <thead>
              <tr>
                  <th>Name</th>
                  <th>Relation</th>
                  <th>Percentage</th>
                  <th></th>
              </tr>
          </thead>
          <tbody>
              <tr data-ng-repeat="user in users">
                  <td>{{user.personalInfo.firstName}} {{user.personalInfo.lastName}}</td>
                  <td>{{user.userRelations.relationshipType}}</td>
                  <td><span ng-if="!isEdit">{{user.personalInfo.percent}}</span><input type="text"
                          ng-if="isEdit" ng-model="user.personalInfo.percent" class="form-control"></td>
                  <td><a ng-click="showEdit()" href="#">Update</a></td>
              </tr>
          </tbody>
          <tfoot>
              <tr>
                  <td colspan="2">Total Percentage</td>
                  <td>100%</td>
                  <td><a ng-if="!isEdit" ng-click="showEdit()" href="#">Update</a><a ng-if="isEdit" ng-click="showEdit()" href="#">Save Percentage</a></td>
              </tr>
          </tfoot>
      </table>
  </div>`
      };
    })

    <div class="container">
    <div class="row">
        <div class="col-md-9">
            <h1>Update User Information</h1>
            <div data-ng-controller="user">
                <div data-ng-controller="userInfo">
                    <user-details user="users"></user-details>
                </div>
            </div>
        </div>
    </div>
</div>

Answer №1

The object users in your response is invalid because the key "personalInfo" is used multiple times. To fix this, you should create an array of objects like this:

users = [{
                    "firstName": "Richardoo",
                    "lastName": "Gil",
                    "maritalStatus": "Married",                    
                    "percentage": "50"
                 },{
                    "firstName": "Richardoo",
                    "lastName": "Gil",
                    "maritalStatus": "Single",                    
                    "percentage": "50"
               },{
                    "firstName": "Richardoo",
                    "lastName": "Gil",
                    "maritalStatus": "Married",                    
                    "percentage": "50"
               }];

To display two tables for married and single individuals,

HTML

<div class="row">
    <div class="col-md-9">
        <h1>Update User Information</h1>
           <div data-ng-controller="user">
               <div data-ng-controller="userInfo">
                  <user-details user="users" userfilter="single"></user-details>
                  <user-details user="users" userfilter="married"></user-details>
               </div>
            </div>
     </div>
</div>

Changes to userDetails directive template function

          <tbody>
              <tr data-ng-repeat="user in users | filter:{maritalStatus:$attrs.userfilter}">
                  <td>{{user.personalInfo.firstName}} {{user.personalInfo.lastName}}</td>
                  <td>{{user.userRelations.relationshipType}}</td>
                  <td><span ng-if="!isEdit">{{user.personalInfo.percent}}</span><input type="text"
                          ng-if="isEdit" ng-model="user.personalInfo.percent" class="form-control"></td>
                  <td><a ng-click="showEdit()" href="#">Update</a></td>
              </tr>
          </tbody>

Answer №2

<tr data-ng-repeat="person in people | filter:{relationshipStatus:personfilt}"></tr>

$scope.sortType = 'x.person'

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

Creating a functional component in React using TypeScript with an explicit function return type

const App: FC = () => { const addItem = () => { useState([...items, {id:1,name:'something']) } return <div>hello</div> } The linter is showing an error in my App.tsx file. warning There is a missing return type ...

What is the process for importing a JavaScript file into a Vue component?

Having trouble importing JSON results into a Vue component? The results are as follows: [{"id":"d023c5e3-ca3c-4d97-933a-1112a8516eee", "score":9001, "updated":"2018-12-07T13:48:33.6366278", "player":Johanna, "category":Funny}, {"id":"398b65fb-e741-4801-b ...

Implementing image loading within an accordion component using React and Material UI

I'm working with a React Accordion component using Material UI. Each time I open a tab in the Accordion, I want to load different images from another div that is located outside of the Accordion. Here is the current code snippet: export default funct ...

Challenges in accurately selecting jQuery elements

Currently on my test page, the display is showing Test Page, which indicates something is appearing, but not in the right manner. I have these jQuery Objects: reviews: Array[3] 0: Object excerpt: "Everything I have had here is insane. SO GOOD. I ...

Using a subheader in conjunction with a virtual repeater in markdown does not function correctly

Currently, I am utilizing angular 1 along with angular material. I am trying to incorporate md-subheader with multiple md-virtual-repeat-containers within an ng-repeat loop. The source code can be found on this codepen. The issue I am facing is slightly c ...

Retrieve country data using AngularJS with Google API

Hi there! I'm currently working on extracting the country name from the Google API and storing it in a scope variable. However, I seem to be encountering issues with the function $scope.getLatLon as it is not returning the expected output. As a newcom ...

The amazing property of AngularJS - Scope

I have saved this HTML code in a file. Here is the HTML : <!-- checkbox 1 --> <input type="checkbox" name="checkbox1" id="checkbox-group1" ng-model="checkbox1" value="group1"> <input type="checkbox" name="checkbox1" id="checkbox-group2" ng ...

Parse JSON data and save information into PHP arrays

My JSON data has a specific structure that I need to reorganize. { "1":{"Itemname":"dtfg","unitprice":"12","Qty":"4","price":"$48.00"}, "2":{"Itemname":"kjh","unitprice":"45","Qty":"7","price":"$315.00"}, "3":{"Itemname":"yjk","unitprice":"76","Qty":" ...

One function is failing to execute properly due to multiple if conditions

Take a look at my JavaScript code below: function showLater1() { if ((vidos.currentTime >= 30) && (vidos.currentTime <= 34)) { lay.style.opacity = "1"; content.style.opacity = "0"; controls.style.opacity = "0"; ...

How to retrieve the primary key of a deserialized object in Django?

I currently have a session storing a list of objects that I need to pass from one view to another. While I know there must be a more efficient way to handle this, that's a problem for another time! To access the list from the session, I use the follo ...

What is the best way to retrieve JSON values based on a key using JavaScript, jQuery, or AngularJS?

Here is some JSON data that I need help with: var jsonData = { "title": "Testing", "settings": { "mySettings": false }, "jsonList": ["TestingList"], "testJsonVals": { "Test1": { "name": "name1", ...

How to associate an object with a component in Angular2/TypeScript using HTTP

I am currently working on displaying a list of item names retrieved from a REST API. By utilizing the map function on the response observable and subscribing to it, I was able to obtain the parsed items object. Now, my challenge is how to bind this object ...

Make sure to wait for the current operation to finish before moving onto the next one

In the primeData function within the datacontext, four queries are made to a back-end Web API service: function primeData(forceRefresh) { return (getLookups(forceRefresh) // this needs to complete before moving on .then(success)) ...

Using protractor's onPrepare feature to set up for various test suites

In my conf.js file, I have an onPrepare function where I handle logging into the application. This function is executed every time I run one or more test suites, allowing me to log in before running any tests. The problem arises when I do not want to logi ...

Utilizing Angular to Fetch JSON Data from a Server

I am currently retrieving data from a JSON file that resides on a server and is updated regularly. It's crucial for me to access this JSON content in order to consistently showcase the most recent information on my website. At present, I have stored ...

Pusher: Received no callbacks for testing the pusher functionality on my event

I am attempting to implement a feature where each object I create is broadcasted without the need to refresh the page. Below is the JavaScript code for initializing Pusher and binding the event for UserHasRegistered: <script src="https://js.pusher. ...

Convert JSON data into the desired format

My JSON input is as follows: [ { "date": { "value": "2022-05-01" }, "parent": { "value": "Choclate" }, ...

Utilizing Zend_Http_Client for sending a JSON object via POST request

I am attempting to send a JSON object as a POST command using the code snippet below: $uri = "http://amore-luce.com/product_create"; $product = $observer->getEvent()->getProduct(); $json = Mage::helper('core')->jsonEncode($ ...

Take out property that was placed in the "style" tag

One particular static HTML file that I have consists of the following code: <style> p { overflow-wrap: break-word; word-break: break-word; hyphens: auto; } </style> <div id="wrapper"> <p>Insert text here ...

How to correctly structure a JSON object in Swift 3

I'm encountering a problem with formatting my JSON object on my Node.js server. My API is configured to accept a JSON object and save it in a database. Everything works fine when I send a POST request using Postman, but I run into an unusual error whe ...