Delay generating directive until after page is ready and responsive - angularjs

I'm working on a single-page app where some parts are really slow. They're slow because I'm displaying 400 complex things in a repeater for the user to scroll through. Each thing is generated by a fairly complex directive that does a ton of data binding and expression evaluation, adds one or two click handlers, and displays a couple of images. In some cases, I also need a grayscale CSS filter on those images, but that really seems way too slow.
I have of course already turned most of my data binding into one-time data binding, but simply generating the 400 things for the first time is still slow. It's initially hidden through ng-if, which speeds it up when I'm not showing it, but once I do need to show it, everything waits 10 seconds for that to happen. I would like to load it in advance, but using ng-show instead of ng-if means the loading of the entire app has to wait for this.
What I would like, is to load the rest of the app, and then, while we wait for user input, start creating these 400 things so they're ready once I need to show them. I don't want the user to notice how slow this is.
Problem is, I have no idea how to do this. Any ideas?
Edit: Having thought about this (and discussed this with my wife), I'm seeing two options (that I conceptually understand, at least):
The easy, quick, boring and cowardly solution is to simply not show the 400 things at the same time, but cut them in pieces and show 40 at a time. That should make it a lot quicker, but also less nice, as the user needs to click around to access all the data.
The interesting solution is to write a new ng-repeat that generates the 400 transcluded copies of the template each in their own asynchronous event, so they don't block user interaction. I really like this idea, but there's one big downside: it's an ambitious idea with deep Angular magic, and I don't have much time available.

OK, not seeing your code structure, through Q&A, I'm trying to get clarification. If I understand you correctly, I believe the solution is to process your images asynchronously and remove reliance of creating/processing them on the fly when the view is visible (i.e. via clicking on a button/tab to 'show' the array 'view' and thus triggering the ng-repeat). BTW, this solution assumes the delays are because the images are being processed rather than because they are being shown.
METHOD 1 (less preferred)
To do this, it's best to create an 'ImageDataService' service, where it get's kicked off at application start, and proceeds with building this array and taking whatever time it needs asynchronously without caring what view is showing or not. This service will be injected into the proper view or directive controller--perhaps where the current ng-repeat scope is.
Meanwhile, you also need to change the directives inside your ng-repeat to get the pre-built data from the array provided by ImageDataService rather than actually doing the calculation at view time. If the data for that directive is not ready, the directive will show something like 'loading...' otherwise, the directive will simply show the prebuilt images. This way, it doesn't matter when ng-repeat is triggered (i.e. its view is showing), because it will just show what are processed and ready at that point and the display the rest as 'loading...'.
METHOD 2 (I prefer this)
Alternatively, and maybe better, you can forego creating a pre-processed array in a service as in METHOD 1 and instead modify your directives to process their data asynchronously by invoking a service method that returns an asynchronous promise like this:
(code inside a controller)
var promise = ImageDataService.processImage(directiveData);
promise.then(function() {...set the directive image attributes..})
Needless to say, the ImageDataService.processImage() method needs to return a promise when it is done processing the data. The directive, as usual, will show 'loading...' until then. Also, although ImageDataService no longer needs to pre-populate its array mentioned in METHOD 1, it might be a good idea to save the processed images to a similar array anyway to serve as cache and not reprocess them needlessly. NOTE, in this case you don't need to have processImage() inside a service--but it is really good 'separation of concerns' practice to reserve the work of asynchronous data processing (ajax, etc) within a service which can be injected app-wide rather than within a controller.
Either of these 2 general tacks should work.

Related

is angulars reloadOnSearch evil?

I've been programming with angularjs for some time now, however, i started using reloadOnSearch for my application and at first i thought this was going to save me for uneccesary reloads of controllers and ajax calls against my API.
For example say i have a list of things, and then present them in a view. When you first access this view it fetches the list of items from the API and presents them, and when you click on an item it adds the ?id=xxx&view=show query parameter to the url without reloading the controller.
When we access a single item from the already loaded list, it just fetches the list item from that we already have and presents it. However, if we forcibly reload the page, the controller now realizes that it has to fetch it from the API instead as it doesn't exist within the list collection.
At first this seemed like a great thing. However as i think about it, i now have to manage the state of the entire controller, whereas before i could have state enclosed within single functions in the controller.
I seem to be having trouble deciding if reloadOnSearch is evil and should be avoided, or if it is worth keeping around. What is your opinion?
Also, would it be better to use something like ui-router instead? I just saw a introduction video which implies that one can have better control of state.
I've converted my app to use ui-router instead. which basically nests application logic in "sub scopes" making it possible to share data between states/pages. I realize now that this is possible without ui-router aswell, however one would have to create pages that has a hierarchy of <div ng-controller>
So in conclusion, the way i was using reloadOnSearch was indeed evil. However, there were better ways of using it aswell.

Angular external template directive in ng-repeat

I have this here block of html, say: <div>{{myVar}}</div>. This block of code is on a lot of pages in a lot of places. The designer from time to time decides to randomly change the way the block looks and what it contains so i have to every page in every place to redo the blocks of code -> BAD!
The solution would be put that block of code in a directive and modify it in one place only. Now said block of code is quite complex markup wise so i'm inclined to put it in a separate page and do a templateURLreference (for ease of editing), but the drawback is that in every place, the directive would sit in an ng-repeat and i'm not sure if angular does a HTTP request for that separate page, where the directive would sit, every time it runs into that directive.
My questions are therefore these:
1) Does Angular do a http request every time it runs into that directive? - is there an option for this not to happen, if it does?
2) What other drawbacks could i run into, if i place it in a separate page?
3) What's the rule of thumb for placing the directive in a separate file.
4) When do you know if you're "overdirectivising" your markup?
Angular fetches the template once and keeps in the cache and serves it from there.
So there is only one http call.
So if you wan't to avoid it you will have to use a string.
And you can do something better here.
Spicify the dummy URL in the directive. And create the template string somewhere.
And in module.run inject $templatecache service and call:
$templatecache.put('url',templateString);
Now your directive will behave its reading from the URL. but you are actually specifying the string at module level.
"This way you can specify all your template string at one place. No need to keep them with directive."
No. It gets the template once, put it in a cache, and gets it from the cache for all subsequent occurrences of the directive. Of course, if the app is reloaded (i.e. the page is refreshed, the template will be reloaded. But even then, unless you explicitely prohibit it, the browser should have it in its own cache.
I don't see any.
I usually do it when the template is too large to be comfortably put inside a JS string literal. Note that you could also put it in a separate file, but embed it in the JavaScript code at build time, if you really don't want an additional HTTP request to load its template.

Is it an antipattern to use angular's $watch in a controller?

In my never ending quest to do things the "proper" angular way, I have been reading a lot about how to have controllers observe the changes in models held in angular services.
Some sites say using a $watch on a controller is categorically wrong:
DON'T use $watch in a controller. It's hard to test and completely unnecessary in almost every case. Use a method on the scope to update the value(s) the watch was changing instead.
Others seem fine with it as long as you clean up after yourself:
The $watch function itself returns a function which will unbind the $watch when called. So, when the $watch is no longer needed, we simply call the function returned by $watch.
There are SO questions and other reputable sites that seem to say right out that using a $watch in a controller is a great way to notice changes in an angular-service-maintained model.
The https://github.com/angular/angular.js/wiki/Best-Practices site, which I think we can give a bit more weight to, says outright that $scope.$watch should replace the need for events. However, for complex SPA's that are handling upwards of 100 models and REST endpoints, choosing to use $watch to avoid events with $broadcast/$emit could end up with lots of watches. On the other hand, if we don't use $watch, for non-trivial apps we end up tons of event spaghetti.
Is this a lose/lose situation? Is it a false choice between events and watches? I know you can use the 2-way binding for many situations, but sometimes you just need a way to listen for changes.
EDIT
Ilan Frumer's comment made me rethink what I'm asking, so perhaps instead of just asking whether it is subjectively good/bad to use a $watch in a controller, let me put the questions this way:
Which implementation is likely to create a performance bottleneck first? Having controllers listen for events (which had to have been broadcast/emitted), or setting up $watch-es in controllers. Remember, large-scale app.
Which implementation creates a maintenance headache first: $watch-es or events? Arguably there is a coupling (tight/loose) either way... event watchers need to know what to listen for, and $watch-es on external values (like MyDataService.getAccountNumber()) both need to know about things happening outside their $scope.
** EDIT over a year later **
Angular has changed / improved a lot since I asked this question, but I still get +1's on it, so I thought I would mention that in looking at the angular team's code, I see a pattern when it comes to watchers in controllers (or directives where there is a scope that gets destroyed):
$scope.$on('$destroy', $scope.$watch('scopeVariable', functionIWantToCall));
What this does it take what the $watch function returns - a function that can be called to deregister the watcher - and give that to the event handler for when the controller is destroyed. This automatically cleans up the watcher.
Whether watches in controllers are code smell or not, if you use them, I believe the angular team's use of this pattern should serve as a strong recommendation for how to use them.
Thanks!
I use both, because honestly, I view them as different tools for different problems.
I'll give an example from an application that I built. I had a complex WebSocket Service that received dynamic data models from a web-socket server. The service itself doesn't care what the model looks like, but, of course, the controller sure does.
When the controller is initiated, it set up a $watch on the service data object so that it knew when it's particular data object had arrived (like waiting for Service.data.foo to exist. As soon as that model came into existence, it was able to bind to it and crate a two-way data-bind to it, the watch became obsolete, and it was destroyed.
On the other side, the service was responsible for broadcasting certain events as well, because sometimes the client would receive literal commands from the server. For instance, the Server might request that the client send some metadata that was stored in the '$rootScope' throughout the application. an .on() was set up in the $rootScope during module.run() step to listen for those commands from the server, gather needed information from other services, and call the WebSocket service back to send the data as requested. Alternatively, if I had done this using a $watch(), I would have needed to set up some sort of arbitrary variable for it to watch, like metadataRequests which I would need to increment every time I receive a request. A broadcast achieves the same thing without having to live in permanent memory, like our variable would.
Essentially, I use a $watch() when there is a specific value that I want to see change (especially if I need to know the before-and-after values), and I use events if there are more high-level conditions that have been met that the controllers need to know about.
With regards to performance, I couldn't tell you which one is going to bottleneck first, but I feel like thinking of it this way will let you use the strengths of each feature where they are strongest. For instance, if you use $on() instead of $watch() to look for changes in data, you will not have access to the values before and after the change, which could limit what you are trying to do.
All that two-way data-binding is, is a $watch on whatever scope property you give to ng-model, which has a controller that allows other directives like input, and form to sync the ng-model value to render the view on a change. Which is detected by their registration of events in the DOM.
In essence,ng-model's $watch compares the value in the model, to the value it has internally. The value it has internally is set by supporting directives (input,form etc).
IMHO The only "events" you should react to in an angular application are user created (ie DOM events). These are solved with directives on the DOM and ng-model linking to the ..model
Also naturally there is async, for which angular provides $q for which the callbacks invoke a $digest.
As for performance, it says it really well in the angular docs. Its run on every $digest. So make it fast. Whats every $digest? Angular traverses all of your active scopes. Each scope has watches. which it executes. and performs comparisons in those. If there are diffs, it will run again. (the next loop around) Its not that simple because its optimized but all of your "angular code" executes in this $digest loop. A lot of directives might invoke a digest with scope.$apply(...) That will cause watches of whatever value they changed to notice and do their thing.
So your original question. Is it an anti-pattern? Absolutely not if you know how to use it. Though I'd just use ng-model. Just because it has had 1.2.10+ iterations of pretty smart people working on it... All of the other 'reactive-ness' of your app can be handled by $q, $timeout and the like.
I think they all have their proper place and, for me, it would be difficult to say stop using one for the others.
Data binding should always be used to keep your data model in sync with changes from the view. I think we can all agree on that.
I think using a watch on a controller to trigger some action based on a data change is useful. Like watching a complex data model to calculate a running total for an invoice. Or watching a model to trigger it as dirty.
I have used broadcast/emit/on when sending a message or an indication of some change from one scope to another that may be several layers away. I have created a custom directive where a broadcast event has been used as a hook to take some action in a controller.

how can I exclude an element from an Angular scope?

my premise was wrong. while AngularJS was certainly slowing things down, it was not due to the problem I describe below. however, it was flim's answer to my question - how to exclude an element from an Angular scope - that was able to prove this.
I'm building a site that generates graphs using d3+Raphael from AJAX-fetched data. this results in a LOT of SVG or VML elements in the DOM, depending on what type of chart the user chooses to render (pie has few, line and stacked bar have many, for example).
I'm running into a problem where entering text into text fields controlled by AngularJS brings Firefox to a crawl. I type a few characters, then wait 2-3 seconds for them to suddenly appear, then type a few more, etc. (Chrome seems to handle this a bit better.)
when there is no graph on the page (the user has not provided enough data for one to be generated), editing the contents of these text fields is fine. I assume AngularJS is having trouble when it tries to update the DOM and there's hundreds SVG or VML elements it has to look through.
the graph, however, contains nothing that AngularJS need worry itself with. (there are, however, UI elements both before and after the graph that it DOES need to pay attention to.)
I can think of two solutions:
put the graph's DIV outside the AngularJS controller, and use CSS to position it where it's actually wanted
tell AngularJS - somehow - to nevermind the graph's DIV; to skip it over when keeping the view and model in-sync
the second option seems preferable to me, since it keeps the document layout sane/semantic. is there any way to do this? (or some, even-better solution I have not thought of?)
Have you tried ng-non-bindable? http://docs.angularjs.org/api/ng.directive:ngNonBindable
<ANY ng-non-bindable>
...
</ANY>

How do I create a new, uh, thing in Angularjs?

I think the vagueness of the question is part of the problem, so my real first question is, what do you call, in Angular, the thing.
The thing I'm trying to name is the view plus the controller, over the model of a single object. I don't even know what to call it. For things I know ahead of time I'm going to need, I've been creating directives, but what do you call one instance of the thing that a directive creates?
I have several situations where all of a sudden (in response to some external event), I have a new object in the model and I want to show it on the screen. Angular seems to want me to list all the possible views ab initio in their parent view, but that isn't really reasonable in my case. How, for example, would I list all the pop-ups and tool-tips and other stuff.
I'm down in some little edge case, deep in the controller code, and it needs to add something to the current view. What's the accepted practice.
Incidentally, the $route/ng-view is one case of exactly this. The view containing the ng-view, and the ng-view DIV itself, have no idea what the $route module is going to put in the ng-view. I need the more general case of this strategy.
EDIT
People keep asking for an example. How about this: I'm making an equipment-requisition app. When a user asks that one of the 1000 different type of equipment be sent to him, I need to display a pop-up that gathers addition information specific to that type. If he asks for a screwdriver, the pop-up will ask about blade size, neck length, and handle composition; if he asks for an airplane, it will be a wizard ask him about engine size, fuel tanks, seating arrangement. All the app knows on start-up is the list of all equipment types, and the name of the UI element that gathers all subsequent information about each particular type.
I'm down in some little edge case, deep in the controller code, and it needs to add something to the current view. What's the accepted practice.
Somewhere, you need to define all of the views you'll need -- e.g., all of the equipment popups. You could put each view into a separate file and use ng-include to dynamically pull in the one you currently need to display. Define a property on your $scope (e.g., $scope.equipmentTypeViewUrl), then
<div ng-include src="equipmentTypeViewUrl"></div>
Since ng-view can only appear once per page, ng-include is probably not what you need to use if you need multiple levels of routing.
See also
create a single html view for multiple partial views in angularjs
https://groups.google.com/forum/#!topic/angular/xIIyGpW8KUk/discussion
App design using Angular js
Client Side Template with view per role
I think the problem is that you think that you need to create the "thing" in controller, but actually you don't. The way two-way data binding works is that you change some attribute value, and the view changes based on that. I've never seen a use case where that's not enough, pop-ups and tooltips notwithstanding.
However, if you really must have the controller show something, you could utilize angular's events to do that. You would need two parts: a directive responsible for showing stuff (modifying DOM), and the controller. The controller would $broadcast an event with some parameters, and the directive would listen to those events using $on and react accordingly.
I'd just make sure I had some useful code coming in as the model...
<div class="row" ng-repeat="attribute in attributes">
<div class="widget" ng-repeat="input in attribute.inputs">
<input type="{{input.type}}" ng-model="input.value" />
</div>
</div>
I'm extremely limited in my knowledge, but all I know is if you have a definite structure to your model you can build a view that reacts to it dynamically.
If all of those things are related to your original object (properties or in some way other) you could loop through the data, display the properties and if need use the keys and filters for a label. Imho it's not really an angular question, more one if your data structure. If you have a good data structure you could use a service for creating a related data-object.
For a related popup, you can use a directive and even process the model data there (only recommended if it has a consistent structure).
If you dislike this approach, you can process the data directly in the template.
But without more specific details, there will be no definite answer.

Resources