Navigating live data and managing the view state within AngularJS

After utilizing AngularJS for a considerable amount of time, I have encountered some challenges with managing data sets.

Imagine having an array of items:

[
 { id: 1, votes: 10, detailInformation: 'Interesting #1' },
 { id: 2, votes: 12, detailInformation: 'Interesting #2' }
]

To keep the user informed with the latest information, I've set a $timer to fetch this data every 60 seconds from a REST webservice.

The presentation of these items to the user is in the following format:

|   ID: {{item.id}}    Votes: {{item.votes}}                                             |
|   <span data-ng-click="item.showInfo = true">Click here to view detail info</span>     |
|   <span data-ng-show="item.showInfo == true">{{item.detailInformation}}</span>         |

Although this setup works well, when the timer updates the content, it resets the view state (item.showInfo = true). How can I effectively manage this client-only state separate from the server data that requires regular updates?

Answer №1

To properly structure your controller, it's important to keep the showInfo function as a separate entity within your code. Avoid including it in the response object received from the server. Instead, define it within your controller like so:

app.controller('test', ['$scope','urService',function($scope,urService){
    $scope.showInfo = true;
    urService.getData(function(data){
       //update data in another scope object
    }
}]);

Answer №2

In order to optimize performance, I recommend storing item.showInfo on a different reference:

JavaScript:

$http.get('/api/endpoint').then(function (data) {
  $scope.items = data;
  $scope.isShown = new Array(data.length); // initializing $scope.isShown when receiving data for the first time
}

HTML:

<div ng-repeat="item in items">
  <button ng-click="isShown[$index] = true">Click here to view detailed information</button>
  <span ng-show="isShown[$index]">{{ item.detailInformation }}</span>
</div>

Answer №3

Shoutout to V31 for sparking the idea, which I then took and made more adaptable:

// Your controller
$scope.items = [] // Holds data from the webservice
$scope.itemsViewState = {} // Map storing all viewstates with ID as key.

The HTML:

<div ng-repeat="item in items">
    ID: {{item.id}} <br />
    Votes: {{item.votes}} <br />
    <span data-ng-click="itemsViewState[item.id] = true">Click to see details</span> 
    <span data-ng-show="itemsViewState[item.id] == true">{{item.detailInformation}}</span>
</div>

If you need to store multiple properties per object, remember to create a map for each level:

// Your controller
$scope.items = [] // Contains webservice data
$scope.itemsViewState = {} // Map with viewstate by ID.
$scope.openDetail = function($item) { 
$scope.itemsViewState[item.id] = {}; 
$scope.itemsViewState[item.id]['subprop'] = true; }

The HTML:

<div ng-repeat="item in items">
    ID: {{item.id}} <br />
    Votes: {{item.votes}} <br />
    <span data-ng-click="openDetail(item)">Click to see details</span> 
    <span data-ng-show="itemsViewState[item.id]['subprop'] == true">{{item.detailInformation}}</span>
</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

Balanced-JS encounters a 404 error

I am currently testing out the code sample provided in the following link: https://github.com/balanced/balanced-js After following the README instructions, I was able to get my local server up and running. However, when I visit the website and try to tok ...

Scrollbar magically disappears within a div

I have a div element on my website with the overflow property set to auto, which displays a scrollbar when the content overflows. I'm looking for a way to hide this scrollbar while still allowing users to scroll within the div. Any assistance would be ...

The reason behind the creation of .pnp.loader.mjs and .pnp.cjs files by yarn

While working on my React project with Vite, I noticed that when using yarn to start the "live server," two new files are created: .pnp.loader.mjs and .pnp.cjs. Can anyone explain what these files are for? I've never come across them before as I usual ...

Tips for modifying multiple divs with the same class using querySelector

I am curious about how to change the class on multiple divs at once using JavaScript. In the example below, only the first use of the class is recognized, while all subsequent ones are ignored. querySelectorAll does not seem to work. Thank you in advan ...

Using JavaScript to Extract Data from HTML Forms

I am currently working on parsing a form using JavaScript, instead of opting for a POST request. The form consists of one input field for the team name and multiple input fields for player names and numbers. <!-- INPUT FORM --> <div id="rosters_c ...

Encase input elements with divs using a directive

Is it possible to simplify and streamline the code for form inputs? If so, how can this be done? For example, I have an input in my form structured like this: <input type="text" class="form-control" name="dirinput" placeholder="Placeholder" ...

Tips for updating data in vue.js

I am currently facing a challenge where I need to use vue.js to edit and update values. While I have successfully implemented the edit functionality to retrieve the values, I am encountering difficulties with updating them. To trigger the update action, ...

Identifying flex-wrap capabilities across different browsers

Currently, I am developing a project that involves implementing a responsive grid using the flex wrap property. However, since my project needs to support IE9 and older versions of Firefox (version 28 and below), I am in need of a way to determine their ...

Using addClass and removeClass with transition does not yield the desired result

As I scroll through the container, I want my menu to change its height, width, and hide its title. I have implemented this functionality, but the transition I added is not working. HTML code: $(window).on('load', function() { $("#container- ...

Error: `THREE is not defined` was encountered in `app.js` on line 3524 when trying to load `three-bmfont-text/index.js`

My goal is to utilize Three.js along with three-bmfont-text in order to generate 3D text and enhance its appearance using shaders. After installing three and three-bmfont-text via npm, I imported them into my JS file: import * as THREE from 'three&a ...

Omit punctuation from the key name in the JSON reply

Hey there, I'm a bit confused about why periods are being used in JSON key names. Basically, what I'm trying to accomplish is passing a JSON response through EJS variables into a page template and extracting the data into separate fields. Here& ...

Validating textfields and dropdowns for dynamic HTML identifiers using jQuery

I am attempting to validate a dropdown and text field together. Both fields can either be left empty or both must be filled. The HTML ids are generated dynamically. I have tried the code below but it is not working as expected. Here are the resources I use ...

Restricting concurrent asynchronous $http get requests in Angular程序

I've set up a page displaying a table of IP addresses connecting to a media stream. I've linked them to a database that includes location information and have managed to serve duplicate IP requests from cache to lighten the load. However, the pag ...

Three.js ShadowMap Tutorial

Currently working with three.js version r73 and encountering two issues regarding shadowmaps. Initially, when I toggle the 'logarithmicDepthBuffer' setting to true for my renderer, shadows no longer appear. Additionally, I am unable to see shad ...

Is there a way to prevent view re-rendering in a Route component in React using react-router-dom?

I have Objects.tsx and Property.tsx views. In Objects I created a Switch with Route to display the Property. <Switch> <Route exact path="/objects/property" component={() => ( <Property /> )} /> < ...

Click the button to automatically generate a serial number on the form

My form includes three input fields: sl no, stationerytype, and stationeryqty. By clicking the symbols + and -, I can add or delete these fields. I am attempting to automatically generate a Sl no in the sl no field when I click the plus symbol, and adjust ...

Is there a way to produce a list of array elements where the initial letter is capitalized?

My current challenge involves trying to capitalize the first letter of each element in the following array. So far, it's only returning the second word as capitalized. var clenk = ["ham","cheese"]; var i = 0; for (i = 0; i < clenk.length; i++) { v ...

Displaying records up to the year 1427 only

I am facing an issue while trying to populate data from a database into an HTML table using JSON and C#.NET. The problem I am encountering is that only up to 1427 records are being displayed, and I keep getting the error message "Unexpected token <". De ...

Async/Await moves on to the next function without waiting for the previous function to finish executing

I am developing a web application that requires querying my database multiple times. Each query depends on the data retrieved from the previous one, so I need to ensure each call completes before moving on to the next. I have attempted using async/await fo ...

Building a webRTC peer using only a JavaScript interpreter, no browser required

My goal is to develop a WebRTC peer that functions solely as a listener/recorder without any graphical presentation like HTML/CSS involved. If achievable using the WebRTC JavaScript APIs, I am curious about which standalone JavaScript engine I should cons ...