Developing widgets in one view in Angular.js - angularjs

I’d appreciate if you could share you view/experience.
Suppose you have a view which contains several widgets that share some of the data (fetched from a server). For example we might have a tree, list and breadcrumbs widgets in the same view, naturally a name of a single item can be displayed in more than one widget at the same time.
My question is what is the best practice of developing such views?
Specifically:
Are the widgets totally independent? (The easiest to implement, but suffer from performance problems)
If the widgets are dependent, do they communicate through:
A single model (introduces tight coupling between widgets and prevents further code evolution)
Events (lose coupling but error-prone due to lose contract, less explicit code)
Any other way
Provided those widgets have their own controllers and scopes, how do you propagate the change notifications from the URL (or any other event) to all of them?
For example if you wanna see an entity with a specific ID using URL routing, do you have a top-most view controller that is responsible to catch this change and notify all the widgets about it using some in-house mechanism, or do the widgets catch the event independently?
I guess all these questions are somehow related so feel free to answer them in whatever form/order you like.
Thanks.

Are the widgets totally independent?
I think that is too broad of a question for us to answer, as that really depends on what the widgets/directives are doing. Are you asking if they should be using isolate scopes? See also When writing a directive in AngularJS, how do I decide if I need no new scope, a new child scope, or a new isolated scope?
do they communicate through...
Again, too broad, sorry... it depends on what the directives do. Besides the ways you already listed, you could also communicate via
a service, which is probably what I'd use if I had more than two directives that needed to communicate
require: 'controllerNameHere'. With the require approach, you would define methods on your controllers using this instead of $scope. This method is limited to essentially one-way communication though: from the directive that has require to the directive that it is requiring. E.g., on the AngularJS home page, the pane directive requires the tabs directive. This allows the pane directive to call methods on the tabs directive's controller, but the tabs directive can not call methods on the pane directive's controller. (For more on this, see 'this' vs $scope in AngularJS controllers)
how do you propagate the change notifications
That depends on the type of scopes your directives have. If you are using scope: true for your directives, you don't have to propagate anything. They can all $watch some parent scope property (and because of the way JavaScript prototypal inheritance works, all of the directives can see the parent scope properties). If you are using scope: {...}, then you can use '=' or '#' to define local directive scope variables and use $watch to watch them.
If you are concerned about performance with $watches (since they are evaluated at least once every digest cycle), then events might be more appropriate.
Another thing to consider: do you want your directives to know about URLs or just scope properties? Using scope properties would likely make your directives more reusable.

Related

Backbone.js app design principles: extending views vs initializing child views

Long story short, let's say one app has multiple pages with:
a form
a list
pagination
each page may require (now or in the future) custom actions to be implemented
My question is, witch is the preferred Backbone way of handling this and why (please argument) ?
Define, a pagination view, a pagination collection, a search model, search view, etc, and initialize each one as a child view in all the necessary pages. This means we will have to append child view elements into the 'master' element, and handle all the communication between these in all necessary pages.
Define a pagination view (with it's own pagination collection and search model) and extending it across all the necessary pages. This does mean that we will have to make use of template partials (for forms, pagination, etc) and bypasses the need of handling communication between child views while also removes the need of appending/removing child view elements.
Please add your way of handling these cases if not found above, remember to argument.
My personal opinion would be 2. And that is because it removes a lot of hustle with communication between child views and it makes everything much more easier to read just by extending classes, instead of having to 'manually' init child views. It also gives one the option to rewrite behavior per page when needed.
I think #2 is a poor choice.
It's a very good idea to keep templates as simple as possible. They are basically just the markup that's generated for some input object. In order to get that object to the template, in MV* frameworks you have Views, that can either pass a model to the template or send some formatted data to the template (I prefer this where possible).
Partials just create markup. You'll still have to handle events, updates to the DOM and rendering inside the view. If you only use one view it will have to handle a lot of things, something associated with poor maintainability and a more bug prone codebase.
You'll either have a lot of code in the views, or you'll end up with a lot of mixins or doing a lot of inheritance - and I have no idea which is worse.
Big things are a lot harder to test and to reason about. Avoid doing big things.
I think that another big problem with the template partials approach is the fact that you cannot rely on type information (something like interfaces), on the object that ends up in the template. It's probably easy to make it work when you have a partial or two that you just created, but, in time this information will get lost, leading to a bad development experience.
You'll need to make sure views unrelated to your changes are kept updated with the partial changes you just made for a feature.
Keep in mind that software is never done. Things always change.
Instead of thinking about relationships between models you'll have another complex challenge that you need to handle: the coupling of views through partials.
The alternative is a lot better. Composing specialized views is a good approach because each has it's own internal, smaller state and just it notifies listeners when some action takes place. Nobody cares about what's going on there until something happens and then you just get concrete data.
Going with #1 helps you deal with complexity in your application while allowing you to reuse them in other contexts.

AngularJS data binding types

I know this is an old and 100 times-answered question, but things are getting more complex with the latest releases, thus causing me a lot of confusion.
I'd like to know what is the difference between the four currently available ways to declare a data binding for an attribute in a directive.
Specifically:
# Text binding
= Two-way binding
& Method binding (although some call it one-way binding)
< One-way binding
I'm interested in particular in the difference between the last two, given that they seem to have overlapping functionalities and I really can't tell the difference and the advantages of one against the other.
# Text binding:
This is used if we want to provide any static text to each instance of our directive. For e.g., any title or specific style/property component that needs to be passed to custom directive that is used to create a dialog.
= Two-way binding:
This is our normal angular two way data binding. For e.g., any live data update in a dialog or any user input (checkbox, radio etc.) can be achieved using this.
& Method binding:
As the name suggests this is primarily used for calling methods defined in the parent controller from the directive. It can also be used to evaluate a expression and bind the result to the directives scope. Typical usage might be responding to user events like when the user closes the dialog.
< One-way binding:
This I guess was introduced for higher performance situations, where we need not any updates from the directives scope to reflect on the parents scope. Typical usage scenario may be when we need to pass title, style, dialog configuration (modal/non modal, etc.) via a variable defined in the parent scope. Since such data are mostly not changed in the scope of the custom directive (our case dialog), one way binding would have a higher performance than a double binding. This is because angular watch cycle needs to monitor only the parents scope variables and not the directives one-way binded variables.
Note: I am not a expert in AngularJS and the answers above are best to my knowledge. They might be wrong in the view of a experienced Angular guy. Please pardon and correct me if there are any mistakes.
Official docs: https://docs.angularjs.org/api/ng/service/$compile#-scope-
Here is some information on the new one-way binding for isolate scope.
From GitHub:1
feat($compile):
add one-way binding to the isolate scope definition
This change allows the developer to bind an isolate scope / controller property
to an expression, using a < binding, in such a way that if the value of the
expression changes, the scope/controller property is updated but not the
converse.
The binding is implemented as a single simple watch, which can also provide
performance benefits over two way bindings.
Closes #13928
Closes #13854
Closes #12835
Closes #13900

How do I change attributes on directive element's parent

I started with a directive that restricted to be used as an attribute, and when used, it would add ng-mouseover to the element it was applied. It seems to be a trivial task, you just need to $compile it, right? Wrong, it will work only until you decide to have an isolated scope. here's jsbin that explains what I'm talking about
I couldn't solve that problem, anyway.
Now, maybe it's possible to solve this dilemma by making the directive restrict:'E' and transclude whatever is inside of it. Works? Sure. jsbin
But now, I realized that I need to apply those mouse events not to the element itself but to its parent. As in the first case where I struggled to add attributes and keep the content without having scopepocalypse, once again I'm having similar headaches.
Can you guys show me one simple example how to make a directive with isolated scope that adds ng-mouseevent attributes to its parent?
Sometimes I feel stupid for deliberately overcomplicating my own life. Maybe I just need to attach good old event handlers to the parent element right from inside of directive's controller? Yes, seems like an easy fix, but that would be conceptually wrong, and againsts angular's traditions, isn't that right?
The angular way would be to never dynamically attach directives to parents if you're implementing the compile or link functions. The compile and link process is a one way street - meaning parents are compiled before children. Sure you can try to go against traffic, but doing so is difficult, risky, and more trouble than it's worth. By adding directives to a parent, and then trying to recompile it, you'll probably end up recompiling directives multiple times, or worse, introducing a subtle memory leak. It's a difficult road, I'd advise against it. It is not the angular way.
Instead of asking yourself, how do I add directives to my parents, ask yourself, how do I add directives to my children? Child directives can communicate to parent directives through the 'require' property. Usually, this is flexible enough to handle most situations.
To answer your second question, it is perfectly acceptable to hook into JavaScript events within a directive definition (how do you think ng-mouseover was implemented?). If you do, you should do so inside your link function.

Backbone main view control

I have a main section of code that initialises of all my views. How should I handle / listen / bind events from the main sections (probably will turn this into a main app view eventually) with elements of these initialised views? I could pass a reference of a view into another view and do something from inside that view but I'd rather have all this logic in the main / parent. Is this possible or good practice?
If they are all DOM events. No, each view should handle it's own DOM events.
If one view needs to know if something is happening in another view...well, there're lots of ways to do it. I'd usually prefer the subscriber/publisher pattern.
See my answer to another question for code examples:
Call a function in another Marionette.ItemView
You do not need Marionette for that.

How to expose a widget directive API

I'm creating a complex directive of a grid widget and I'm not sure where should I expose the grid directive API, i.e. it's properties (e.g. selectedItems) and methods (e.g. scrollRowIntoView(rowIndex)).
The options I'm considering are:
Expose the API on the scope (my directive defined an isolated
scope).
Expose the API in the directive's controller (if I
understand correctly this is what was done in the
ngFormDirective).
Expose a grid object on the scope which in
turn exposes the API.
Some kind of mix between the previous
options (e.g. properties exposed on the scope, methods in the
controller).
What I want to know is:
Is there a best practice for this use case?
What are the pros and cons for each alternative?
Are there any other valid alternatives?
Thanks!
Generally, you want to expose the bindings as attributes on your directive. That is, if I want to bind my array someItems to your grid, I'd expect your directive to look something like this: <my-grid my-items="someItems">.
You can expose hooks as attributes as well for things like "Run this function when the grid is resized". If I have a whenGridResized function on my scope, I'd want to set that as an attribute as well, like this: <my-grid onresize="whenGridResized()">.
In other cases you can't really use attributes, like your scrollRowIntoView() example. That would be a good candidate to expose in the directive controller, since that is something the directive user might want to call when other things occur in the system (such as DOM events).
So you should expose your API as attributes for events that happens inside your grid (things that you control), like onresize and ondelete or whatever. You can of course expose them in a controller as well.
When your directive needs to react to outside events like scrollRowIntoView(), you would to expose that in the directive controller since it would be a clunky API to expose such hooks as attributes.
You shouldn't expose your API through the scope since you want an isolated scope for your grid. Exposing it through the scope would mean that you have to set it your scopes parent, and it's almost never a good idea to access the parent scope directly.
TL;DR
A rule of thumb would be to expose as much as you can as attributes, and methods on your directive controller when attributes doesn't make sense. Exposing the same functionality in both attributes and your controller is a good idea since it's hard to anticipate how your users will use your directive.

Resources