Cookbook

Recipes for common AngularTS problems

Use the cookbook when you have a concrete problem and need a working pattern. Start with debugging if AngularTS is new to you. Every progressive recipe ends with a task to apply and checks that prove it worked.

Find recipes by area

Start with beginner recipes, then choose forms, HTTP, DOM updates, security, performance, data correctness, navigation, operations, or advanced browser work.

Choose who owns the result

Start from the result your application needs, not from a directive name.

Needed resultStart with
The server already knows the final HTMLSwap server-rendered HTML
One interaction needs JSON and local template stateBuild and submit forms
Several features share records and write operationsRead, write, and prefetch REST data
The browser must own URLs, history, and nested viewsAdd browser-owned routes
The server pushes one-way updatesReceive live server events
The browser and server both send live messagesExchange WebSocket messages
Existing computation blocks rendering after measurementMove measured CPU work to a worker
The measured runtime contains unused featuresBuild a smaller production runtime

Prefer the first applicable row. Do not introduce a client route or shared data service when one server response and one declarative interaction solve the problem.

Start here

  1. Debug a running application
  2. Select an element with ng-el
  3. Pass server data without another request
  4. Update existing DOM from state
  5. Replace DOM from state
  6. Swap server-rendered HTML
  7. Run effects outside the DOM
  8. Handle events
  9. Build and submit forms
  10. Read, write, and prefetch REST data
  11. Authenticate requests
  12. Cache REST reads
  13. Add browser-owned routes

Change server data

Data correctness: handle uniqueness races, submit money safely, send dates with zones, and keep identifiers opaque.

HTTP behavior: revalidate with ETag, serve maintenance responses, validate return redirects, standardize errors, and negotiate page or fragment.

Browser and content security: sanitize rich text, deploy CSP, harden session cookies, support password managers, and redact secrets.

Interaction details: focus the first error, design an empty state, and preserve focus after swaps.

Transaction workflows: respect rate limits, run background jobs, make critical writes idempotent, save multi-step forms, and apply bulk actions.

Account and record workflows: archive and restore, handle permission rejection, keep filters in the URL, and log out safely.

Production form workflows: show server validation, send CSRF proof, confirm deletion, and resolve concurrent edits.

Production response workflows: retry a failed read, paginate on the server, download with the browser, and swap trusted server HTML.

Keep important forms usable with progressive enhancement, and define their HTTP response contracts before wiring the success and failure branches.

ProblemRecipe
Edit one record without leaving the pageEdit a server record in place
Delete one row without rebuilding its listDelete a row after server confirmation
Search without stale responses winningSearch while the user types
Load choices from another fieldLoad one select from another
Show a reversible change immediatelyUpdate immediately and roll back
Upload a file and allow cancellationCancel a file upload
Choose status, content type, and bodyDesign an HTTP response

Load and navigate faster

ProblemRecipe
Data should be ready before clickPrefetch data before the user clicks
More rows should load near the viewportLoad the next page near the viewport
Stable lookup lists repeatCache reference data safely
A private request finds an expired sessionReturn users to login
A dialog needs current server contentLoad a dialog from the server

Add specialized browser behavior

Integrate another framework

Start with the integration decision guide, then use the event bus for transient messages, ng-observe for reflected web-component attributes, or a shared application model for current reactive state.

Diagnose a production problem

Production change management: deliver server flags, record audit events, and roll contracts out compatibly.

When an API must use another origin, follow the cross-origin request recipe before adding browser workarounds.

Make failures traceable with a request ID, then run the shipping check against the complete interaction.

Trace one interaction with the HTTP debugging recipe, then control repeated requests only after measuring them. Before shipping, audit the full server-driven interaction.

ProblemRecipe
A server page needs one interactive widgetAdd behavior without making an SPA
A component changed state but DOM did notMake a component view reactive
Refreshed rows lose focusKeep repeated rows stable
Hidden UI keeps doing workStop hidden UI work
An older request winsIgnore stale request results
A listener survives its UIClean up browser resources
An interaction feels slowFind the slow part
Request states are incompleteRender every request state

Debug a running application

Read and change scopes, controllers, and services from browser DevTools

Select an element with ng-el

Let AngularTS place a native DOM element on a scope or controller

Pass server data with ng-init or ng-setter

Initialize scope state once or keep it synchronized with server-rendered content

Update text, classes, styles, and visibility

Let bindings update existing DOM when scope state changes

Replace part of the page from state

Add, remove, or switch DOM subtrees with structural directives

Swap server-rendered HTML into the page

Select a target and insert, replace, append, or remove server HTML

Run an effect when state changes

Use scope watches for work outside AngularTS bindings

Handle DOM and scope events

Respond to browser events and communicate through the scope tree

Build and validate a form

Bind fields, show useful errors, and submit valid data

Read and write REST resources

Define a typed endpoint once and use it for CRUD operations

Authenticate requests

Configure cookie or bearer credentials once for framework services

Cache REST reads

Add cache-first, network-first, or stale-while-revalidate behavior

Add application routes

Register states, render them in ng-view, and protect private pages

Load content when it enters the viewport

Delay below-the-fold work with ng-viewport

Receive live server events

Update scope or append HTML through Server-Sent Events

Move CPU-heavy work off the main thread

Run JavaScript in a Web Worker with ng-worker

Load a WebAssembly module

Expose WebAssembly exports to scope with ng-wasm

Edit a server record in place

Load an editor, submit JSON, and keep server validation beside the field

Delete a row without rebuilding its list

Let the server authorize deletion and remove only the successful row

Search while the user types

Debounce requests and ignore responses for an older query

Load one select from another

Request valid choices when a parent selection changes

Load the next page near the viewport

Append server-rendered rows and replace the paging marker

Update immediately and roll back on failure

Show a local change first while preserving the previous server value

Return users to login after a session expires

Route a failed private request and preserve the intended destination

Cache reference data without sharing user data

Cache stable lookup lists and invalidate them deliberately

Cancel a file upload and handle server rejection

Send FormData, abort through timeout, and distinguish cancellation

Load a dialog from the server

Swap server-rendered dialog content and restore focus on close

Understand the similarity to HTMX

Compare the server-first approaches without assuming compatibility

Design an HTTP response for the UI

Choose status, content type, and body before writing the directive

Make a server-driven interaction accessible

Preserve keyboard behavior, announce loading, and move focus deliberately

Audit a server-driven interaction before shipping

Check authorization, CSRF, HTML trust, caching, uploads, and errors

Keep a form useful before AngularTS starts

Build a normal server form first, then add faster in-page behavior

Debug an HTTP interaction from the browser

Trace an element, its scope, its request, and the resulting UI state

Control repeated requests

Measure duplicate work, then delay, throttle, cache, or cancel it

Show validation errors returned by the server

Keep validation authoritative on the server and render field errors in place

Protect a cookie-authenticated form from CSRF

Send a server-issued proof with every state-changing form request

Confirm a destructive action in place

Require an explicit second action before sending a delete request

Handle two people editing the same record

Detect stale updates and let the user compare the current server value

Let the user retry a failed read

Keep the last useful state and retry only when the user asks

Paginate a large result on the server

Keep URLs shareable while replacing only the result region

Download a generated file with the browser

Use normal navigation for files instead of loading bytes into application state

Replace a region with trusted server HTML

Keep rendering on the server without compiling untrusted markup

Show a request ID when an operation fails

Give users and operators one safe identifier for tracing a failure

Check a server interaction before shipping

Walk one feature through behavior, failure, access, and operations

Recover from a rate-limited request

Respect 429 responses without hiding retries or multiplying traffic

Run slow work as a background job

Start work quickly, expose status, and download the finished result

Make a critical write safe to repeat

Prevent double charges, sends, and submissions with an idempotency key

Build a multi-step form on the server

Save each step independently instead of keeping a fragile browser-only draft

Apply one action to several records

Submit explicit selections and return a result for every record

Archive first and offer restore

Make a destructive-looking action recoverable when the domain allows it

Handle a permission rejection without hiding it

Let the server decide access and give the user a useful next step

Keep search and filters in the URL

Make filtered results reloadable, shareable, and usable without JavaScript

Log out with a state-changing form

End the server session, clear private state, and avoid logout links

Keep requests same-origin unless they must cross origins

Configure CORS and credentials deliberately for a separate API origin

Handle a uniqueness race on submit

Let the database decide uniqueness and return the conflict to the field

Submit money without floating-point surprises

Send a decimal string and perform currency arithmetic on the server

Submit dates and times with an explicit time zone

Distinguish calendar dates, local times, and exact instants

Keep identifiers as opaque strings

Avoid rounding, parsing, and leaking meaning through record IDs

Revalidate a cached response with ETag

Return 304 when unchanged instead of transferring the same representation

Keep a useful page during planned maintenance

Return a clear 503 response while preserving public navigation and recovery

Return users safely after sign-in

Preserve a destination without creating an open redirect

Return one safe error shape

Make expected failures predictable without hiding their HTTP meaning

Make full-page and fragment responses explicit

Let one server route return the representation the request actually needs

Render user-authored rich text safely

Sanitize stored markup and keep it separate from application templates

Add Content Security Policy in report-only mode

Measure executable-content dependencies before enforcing a restrictive policy

Harden an authentication session cookie

Keep session credentials out of JavaScript and restrict browser delivery

Build a password-manager-friendly sign-in form

Use normal controls and autocomplete values before adding custom behavior

Keep secrets out of errors and logs

Return safe diagnostics while preserving enough context to trace failures

Focus the first field rejected by the server

Move keyboard users directly to a field-level validation problem

Turn an empty result into the next action

Distinguish no data from loading and failure, then explain what to do

Preserve focus when replacing server HTML

Keep the trigger stable or move focus to a deliberate result heading

Deliver a feature flag with the server page

Avoid a second request and keep authorization separate from rollout

Record who changed sensitive data

Write an audit event in the same server operation as the state change

Roll out a request contract without breaking old pages

Expand, migrate, and contract server behavior across cached browser versions

Find a beginner recipe

Start with inspection, server data, DOM wiring, events, forms, and HTTP

Find a form recipe

Solve validation, uploads, conflicts, multi-step flows, and sensitive input

Find an HTTP recipe

Choose statuses, bodies, caching, retries, fragments, and origin policy

Find a DOM recipe

Select, update, replace, animate, and focus application-owned elements

Find a security recipe

Protect requests, sessions, redirects, content, credentials, and permissions

Find a performance recipe

Reduce requests, rendering, transfer, and main-thread work after measuring

Find a data correctness recipe

Preserve identity, precision, concurrency, validation, and audit history

Find a navigation recipe

Keep URLs, server pages, router states, sessions, and redirects coherent

Find an operations recipe

Trace failures, survive outages, control rollout, and explain sensitive changes

Find an advanced browser recipe

Use effects, viewport events, streams, workers, WebAssembly, and specialized UI

Exchange live messages with WebSocket

Build a bidirectional chat channel with reconnect and cleanup

Integrate AngularTS with another framework

Choose DOM ownership, messages, observed attributes, or shared reactive state

Send messages across framework roots

Use the application event bus for asynchronous cross-boundary notifications

Read Fluent UI custom-element state with ng-observe

Mirror reflected web-component attributes into AngularTS scope

Share current state through an application model

Give AngularTS and another framework one reactive domain object

Build a smaller production runtime

Compose, bundle, measure, and verify only the AngularTS features an application uses

Add behavior to server-rendered HTML

Enhance one part of a page without building an SPA

Make a component view reactive

Fix state changes that do not update a typed component view

Keep repeated rows stable

Preserve row DOM when refreshed data represents the same records

Stop hidden UI from doing work

Choose between removing UI and only hiding it

Ignore stale request results

Keep older responses from replacing newer search results

Clean up browser resources

Stop listeners, observers, and timers when a view is removed

Find the slow part of an interaction

Measure whether delay comes from JavaScript, layout, rendering, or the network

Render every request state

Show loading, success, empty, and error states without contradictory UI