Numerous Cycles Stemming from a Single Answer

My goal is to display a list of products with their details, including a sublist of product models that are checked in the detailed list. The challenge is to achieve this using only one GET request. This means retrieving the JSON data of products once and reusing it multiple times on the page.

Below is my product list with details:

<div class="box-content" ng-controller="PostsCtrl" ><div>
<input type="search" ng-model="search"></div>
<table class="table table-striped table-bordered bootstrap-datatable datatable dataTable" id="DataTables_Table_0" aria-describedby="DataTables_Table_0_info">
<thead>
<tr>
<th><tags:label text="productid"/></th>
<th><tags:label text="main.category"/></th>
<th><tags:label text="sub.category"/></th>
<th><tags:label text="brand"/></th>
<th><tags:label text="model"/></th>
<th><tags:label text="sku"/></th>
<th><tags:label text="active"/></th>
<th></th>
</tr>
</thead>
<tbody>
    <tr id="actionresult{{$index + 1}}" ng-repeat="post in posts | filter:search">
    <td>{{post.productid}}</td>
    <td>{{post.subcategory}}</td>
    <td>{{post.subcategoryid}}</td>
    <td>{{post.brand}}</td>
    <td>{{post.model}}</td>
    <td>{{post.brandid}}</td>
    <td><input type="checkbox" ng-model="checked" ng-checked="post.isactive"></td>
    </tr>

List of models:

<ul ng-controller="PostsCtrl">
  <li ng-repeat="post in posts | filter:checked">{{post.model}}</li>
</ul>

Here is my controller:

<script>
    var app = angular.module("MyApp", []);

    app.controller("PostsCtrl", function($scope, $http) {
      $http.get('http://localhost/admin.productss/searchwithjson').
        success(function(data, status, headers, config) {
          $scope.posts = data;

        }).
        error(function(data, status, headers, config) {

        });
    });
    </script>

I believe my current implementation involves two requests and does not enable listing of checked models. How can I enhance my code to achieve this?

Thank you.

Answer №1

Option 1:

To arrange both elements under the same controller, follow this code snippet:

<div class="box-content" ng-controller="PostsCtrl" >

    ...Some other html....

    <table>
        <tr id="actionresult{{$index + 1}}" ng-repeat="post in posts | filter:search">
            <td>{{post.productid}}</td>
            <td>{{post.subcategory}}</td>
            <td>{{post.subcategoryid}}</td>
            <td>{{post.brand}}</td>
            <td>{{post.model}}</td>
            <td>{{post.brandid}}</td>
            <td><input type="checkbox" ng-model="post.checked"></td>
        </tr>
    </table>

    ...Some other html....

    <ul>
        <li ng-repeat="post in posts |  filter:{checked:true}">{{post.model}}</li>
    </ul>

</div>

Option 2:

To store the request in a cache within the controller, use the following script:

app.controller("PostsCtrl", function($rootScope, $scope, $http) {
  $rootScope.cache = $rootScope.cache || {};

  if(!$rootScope.cache.posts){
      $http.get('http://localhost/admin.productss/searchwithjson').
        success(function(data, status, headers, config) {
            $rootScope.cache.posts = $scope.posts = data;
        }).
        error(function(data, status, headers, config) {});
  } else {
      $scope.posts = $rootScope.cache.posts;
  }
});

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

Removing a key from an index signature in Typescript - a step-by-step guide

In my web application built with Angular, we encountered a need for a data type to store translations of strings in different languages. To address this requirement, a team member defined the following type: export class TranslatedString { [language: str ...

Clicking on a Vue.js element does not trigger the function when an <a> link is present

I am attempting to create a notification system where clicking on the notification and accessing its link will result in a decrease in the total number of notifications.<li class="header">You have {{ notificationsCount() }} notifications</li> & ...

What is the best way to eliminate duplicate items in JavaScript?

Note: I am aware that we use Set to eliminate duplicates in an array. I have a date dropdown. When I select a date, it displays the date correctly in a list. However, the problem arises when I select an already chosen date, it still shows up in the list. ...

Numerous pie charts created from data retrieved through multiple ajax requests

Hey there! I'm looking to create 3 pie charts side by side, each based on a different dataset retrieved through separate ajax calls. The first chart will be generated from the results of one call, the second from another, and the third from yet anothe ...

Is there a way to retrieve the value of an element by clicking on its corresponding button using MUI framework?

I am working on a dashboard feature where I need to update the status by clicking on it. However, I am facing an issue with changing the state value upon clicking. Here is my component: <MenuItem> <Button fullWidt ...

An easy CSS conundrum when hovering

Looking for some assistance with CSS. I want to display the text "Featured Page" with a picture appearing on the right side upon hovering (mouseover). Currently, the picture shows up under the text using the following CSS, but I need it to be larger and pl ...

Using AngularJS to present text based on a boolean value

I'm working with HTML and AJS where I am trying to display the value Is Boss? : true based on the boolean value of person.IsBoss. <span>Is Boss? :</span> <span> {{ person.IsBoss }}</span> However, instead of displaying true o ...

Angular UI and Node backend causing CORS issues

Just diving into the world of node and could use a little assistance. Encountering this error message: Access to XMLHttpRequest at 'http://localhost:3000/api/auth/signin' from origin 'http://localhost:4200' has been blocked by CORS pol ...

Implementing a method to allocate rewards to individual players within a game Bank using arrays in Node.js and JavaScript

In my interactive game, players can choose between two sides to place their bets. At the end of the game, there will be one side declared as the winner and those who placed winning bets will receive a portion of what they wagered. However, I am facing an i ...

Is it possible for the ajax url option to accept an array of URLs rather than just one?

Is there a way to retrieve and store data from multiple JSON URLs in an array? <script type="text/javascript"> urls = ["https://spreadsheets.google.com/feeds/list/1RsiDuydBBHyu4OBjlxq1YH6yT3qcJDMB6-YKU-xxd_k/od6/public/basic?hl=en_US&alt=jso ...

I'm experiencing issues with gson returning null values while attempting to parse a JSON object in Android Studio. What could be the cause

As I work with JSON and GSON to convert it into an object for my app's image display, I encounter a puzzling issue: the imageURL field seems to be returning null values despite not being null in the original json data (check link below). Original JSO ...

Are there any methods to determine the way in which a user has absorbed the content of a post

This particular question sets itself apart from the one found here, as it aims to detect various user behaviors beyond just browser activity. Specifically, I am interested in identifying behaviors such as: Rapidly skimming through an article from start ...

Emberjs 1.0: Data Changes don't Refresh Computed Property and Template

In my Ember.js application, I am using a datepicker which is integrated for selecting dates. When a date is clicked on the datepicker, a computed property should compare the selected date with the dates available in the timeslot to check for a match. Based ...

Troubles arising while using ng serve in Angular 2

I'm currently facing an issue during the installation process of an existing Angular application. When trying to run the application using the ng serve command, I encounter the following error message: The "@angular/compiler-cli" package was not prope ...

Issue encountered when reading CSV files in Firebase functions

My goal is to read a csv file within a firebase function in order to process the data and perform further operations. import * as csv from "csvtojson"; const csvFilePath = "<gdrive shared link>" try{ console.log("First M ...

What steps can be taken to retrieve data from a database table using JavaScript?

I am encountering a very peculiar issue. The values that I need are visible when I receive them as a message from the server-web console. However, when I try to retrieve them using a for loop, I encounter an error 05-22 18:58:23.203: I/Web Console(29392): ...

Create a new NVD3 graph with a vertical line added

I am working with a NVD3 graph that displays a simple data set. My goal is to draw a line over the graph in a different color (similar to a cut-off value, which will be at x=5) <meta http-equiv="content-type" content="text/html; charset=UTF8"> <s ...

Determine changes in data retrieved from a JSON file using React

I've been working on a cryptocurrency app using React and a JSON API to fetch the latest data. My approach involves using fetch to load the JSON API and setInterval to refresh the app every 10 seconds. Now, I'm wondering if there's a way to ...

What could be causing the error I'm encountering while running the 'net' module in Node.js?

I am currently working with .net modular and have opened TCP port 6112. var net = require('net'); var server = net.createServer(function (socket) { //'connection' listener }); server.listen(6112, function () { //'listening ...

Locate the quantity of items in a JSON file

Check out the json data below: [ { "amount": 1, "object": "this" },... ] I'm trying to display the amount for this for obj in parsed: if 'object' in obj and obj['object'] == 'this': ...