Skip to content

Backend Info and the Angular Digest Cycle

August 10, 2016

Seperation of concerns is one of the most important maxims of the web industry. To that end, we build our backends agnostic to their front ends and use http requests and json APIs. When your http requests come back with a chunk of json for the front end to display for user manipulation, you often find that you want to attach front end specific information to this newly received back end info.

Say you are developing a chat client whose backend returns an array of json messages. You want to attach a boolean to every message object determining whether or not the timestamp of the message is displayed.

When do we append this information to the object? Surely not on the backend, whose job it is to be front end agnostic. Do we loop through the messages upon the success of http request and set each message.showTimestamp to false? Gross. Some may try to use ng-init to initialize showTimestamp, but ng-init is not double bound so it does not dynamically change with the model. Directives are complex and may present a solution, but they often expect varying data to be passed in, unlike the initialization logic we need.

What seems to be the best solution is to create a controller for every message object. Typically we think to use controllers to wrap static items, usually one per feature, however the main use case of a controller directly fits our needs, namely “[to set] up the initial state of the $scope object.” We can, within the controllers initialization logic, extend our existing $scope to include a showTimestamp for each message.

This proposed controller would be, like the ideal controller, very lean, containing only the relevant DOM facing data and functionality. The new controller’s $scope is doubly bound and updates with the Angular digest cycle, unlike our ng-init or back end append solutions.


From → Networking

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: