Home > Web Front-end > JS Tutorial > Smart Front-ends & Dumb Back-ends: Persisting State in AngularJS

Smart Front-ends & Dumb Back-ends: Persisting State in AngularJS

Joseph Gordon-Levitt
Release: 2025-02-18 09:48:13
Original
625 people have browsed it

Smart Front-ends & Dumb Back-ends: Persisting State in AngularJS

User interactions with a website generate application state—for example, button clicks or text input. This state, residing in the browser's RAM as JavaScript objects (arrays, strings, etc.), needs persistence. This article explores techniques for persisting this state, distinguishing between temporary and essential data.

Key Concepts:

  • State Persistence in AngularJS: Maintaining user data and application settings across page refreshes and application restarts. Essential for single-page applications (SPAs).
  • Methods for Persistence: AngularJS doesn't inherently support state persistence; methods like cookies, local storage, and session storage are used. These store data client-side, retrieving it even after page refreshes.
  • Demo Application: The accompanying demo uses localStorage. On app load, it retrieves saved data or creates a sample. Edits are saved on input field blur.
  • Smart Front-end, Dumb Back-end: The article advocates a design where the back-end acts as a synchronization server, handling simple storage tasks. Complex business logic resides in the front-end, enabling an offline-first experience. This approach increases back-end technology agnosticism, prioritizing availability, backups, and speed.

Getting Started: Separating Temporary Data

Consider an array of objects, some with temporary keys. These temporary keys shouldn't be persisted. The example uses an AngularJS app, marking temporary keys with an underscore prefix. Initial HTML:

<div ng-repeat="thing in things track by thing.id" ng-click="thing._expanded=!thing._expanded">
    <div ng-if="thing._expanded">EXPANDED VIEW</div>
    <div ng-if="!thing._expanded">collapsed view</div>
</div>
Copy after login

Initial JavaScript:

angular.module('app', []).controller('Ctrl', ($scope) => {
    $scope.things = [
      {id: 1, key: 'Value'},
      {id: 2, key: 'Value2'},
      {id: 3, key: 'Value3'},
    ];
});
Copy after login

Persisting State in localStorage

To persist $scope.things (e.g., a todo list), we need to selectively save data. Temporary attributes (like _expanded) can be regenerated. Simple localStorage.setItem won't suffice because it saves unwanted data. We need a deep copy and data filtering:

let copy = Array.from(myArray, (item) => {
  let obj = Object.assign({}, item);
  for (let key of Object.keys(obj)) {
    if (key.startsWith('_') || key === '$$hashKey') {
      delete obj[key];
    }
  }
  return obj;
});
Copy after login

angular.toJson(myObject) can remove AngularJS's $$hashKey. Using ng-repeat="thing in things track by thing.id" prevents $$hashKey generation.

Enhanced Demo Application: Weekly Log

A more practical demo is a weekly log, allowing text input for each day. The HTML includes input fields and uses ng-blur to trigger saving. The JavaScript handles data preparation, deep cloning, filtering, and localStorage persistence.

Conclusion: The Future of Front-end and Back-end Development

This approach is scalable and realistic. The trend is towards smarter front-ends and simpler back-ends. The back-end becomes a synchronization server, handling data storage while the front-end manages complex business logic. This enables offline-first applications and increases back-end technology flexibility. The demo uses localStorage, but alternatives like Kinto, PouchDB, or Firebase easily replace it.

Frequently Asked Questions (FAQ): (This section remains largely unchanged from the input, as it's a helpful addition and doesn't require significant rewriting for paraphrasing.)

What is the significance of persisting state in AngularJS?

Persisting state in AngularJS is crucial for maintaining user data or application settings even after the page is refreshed or the application is restarted. This is particularly important in single-page applications where the state needs to be maintained across different views. Without state persistence, any data entered or changes made by the user would be lost upon refreshing or navigating away from the page, leading to a poor user experience.

(The rest of the FAQ section follows similarly, as it's already well-written and informative.)

The above is the detailed content of Smart Front-ends & Dumb Back-ends: Persisting State in AngularJS. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template