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
Related
two-way binding feature in angular is so popular, and according to angular community it is good when compared with one-way binding.
And there are lots of simple examples to explain how it works.
But my question is where does we use that feature in real applications.
- One example is using with input boxes, other than that is there any good uses of it?
Two way binding as a default wasn't wise because it creates perf issues (~2000 watchers and your app can go bad fast). It led to the introduction of {{::}} binding syntax (bind once syntax) in Angular 1. Overall I can't see where I agree that default two way binding is said to be a good thing by any knowledgeable Angular dev.
I can tell you for a fact, having written an application that displayed many lists of different kinds of objects simultaneously, that default two way binding was a mistake. It created far too many persistent watchers. The community overall seems to strongly agree.
So what you suggest here is correct; there are uses for two way binding. But those needs should be seen as few and far between. And even then, you could probably get around the need for it at all with a little thinking.
For me, two way binding is primarily useful for input fields. But the mechanism is most definitely downplayed now, it should be used sparingly.
Well, when you bind a label with a $scope variable, though the binding is two-way (by definition) it is only relevant in the direction JS -> HTML.
A two-way binding is only fully exploited in cases where the value can also be changed by the user, meaning any type of INPUT component (textbox, dropdown, checkbox, etc.).
One trivial (though one-directional) example is when you have a page that can be displayed in many languages. You would deploy $scope variable all over, and assign to them strings in the current language.
When the user switches language, the simple assignment of the new strings to the corresponding variable will yield the screen to be automatically update to the new language.
Two way binding is cool when the bound variable can change often, but there are cases where the variable won't change after getting assigned, or will only change once.
Is there a way to tell angular that a binding won't be needed to get monitored anymore for changes after being assigned, or after changing just 1 time?
(for angular 1.x)
Yeah they introduced (think it was in 1.4) the {{::}} binding, so for example:
<p>{{::ctrl.text}}</p>
Will only be bound once.
More details can be found in the documentation for bindings under "One-Time binding"
If you are using AngularJS 1.3 and above
You can use feature called one-time binding
Syntax:
{{::myVar}}
From Docs
An expression that starts with :: is considered a one-time expression. One-time expressions will stop recalculating once they are stable, which happens after the first digest if the expression result is a non-undefined value
You can further read about it here.
If you are using 1.2 and earlier
You can use BindOnce.
While a one-time binding is what you're looking for, I suspect the real reasoning behind your question is performance:
ng-bind is actually still faster than a one-time binding.
Source
I have a question about the difference between Angular 2 two-way and one-way data binding. As I understand, one-way data binding is used for data that flows from parent to child. However, if the source of the binding is a reference to an object, the modifications made by the child are reflected on the parent (through the reference). So how is this different from two-way data binding? Or do I misuse one-way binding, and should use two-way when the child modifies the data?
Thanks
Two way Data binding is Between View and Controller ...
In Simple Words
Two Way
Changes made in view will reflect in Controller
Changes made in Controller will reflect in View
One Way
Once you set the value it will not affect the View or Controller for further changes
You start to have issues with one way bindings when you bind to collections or objects. As you have said, one way binding to a reference doesnt project you from modifying the referenced object as the binding is only shallow, and reflects the value of the reference.
The solution to this is to attempt to use immutable types. As changes to immutable types produce a new reference, this will make one way bindings update every time your object changes.
There are a number of ways to acheive this, from building your own immutable types, using immutable-js, or trying to follow the flux pattern (or using something like redux)
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.
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.