Where does angular two-way binding is useful? - angularjs

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.

Related

Interpolate a one-time binding manually

How could I interpolate a one-time binding manually?
Here is my use case.
I have a list of a lot of elements. The elements just sets of controls. I get the data for the elements from the BE. Then I would like to leverage the AngularJS interpolation and set the controls` values. But I would like to avoid the interpolation of all the elements every time I change only a single control.
So, I use a one-time binding to set the values, but then when I change them they are not updated.
The expected result in the example is that once something is typed in the control, the respective one-time binded value is updated. Also, the one-time binding should remain there, since in my real case there will be a lot of controls and I do not want to strain performance when only one control is interacted with. A simplified example of mine can be found here (in my real case I have not only inputs, but checkboxes as well, but I believe that the approach should be the same for them).
After a research I found out that a directive should be used in this case. But I was not able to find a simple to understand example. So, could someone post it here, please?
Different from a directive solutions are welcome here as well.
First to understand your problem: Why do you want to avoid the angular change detection here? The only reason that comes to my mind would be heavy performance problems.
In one case here, there were one or two thousand of inputs, all with a binding. The application was a little sluggish, but still usable. We accepted this, as we had to re-implement all the binding manually otherwise.
If your binding is rather simple (no validations, conversions, etc.) and the values are not shown on other places while being edited, maybe it would be a way for you to use an AngularJS directive on a native HTML Input element that just listens to its onChange event to save changed data and gets updated programmatically whenever you know it changed from outside (if it does at all).
(Not talking about better using Angular, which has a much tighter grip on change detection ;-) ).

What are the cons of a data binding framework?

I've seen many data binding frameworks, such as WPF, AngularJS(Javascript), JSTL(JSP).
They are trying to separate UI and Data completely.
However, one main problem is that it adds complexity. Sometime, you have to write a lot of extra code (for example to extend a view class) just for one line of UI code.
In modern applications, there are many transition animations when changing one UI element from one state to another state. When use data binding framework, it seems not easy.
Are there any other cons of using a data binding framework?
For example, to set focus on a text input, so complex in AngularJS, See:
How to set focus on input field?
All of the following refers to the WPF.
You have to write a lot of extra code (for example to extend a view class) just for one line of UI code.
With regard to the WPF, this is rare situation, you can give an example?
There are many transition animations when changing one UI element from one state to another state.
In WPF since version .NET 3.5 appeared VisualStateManager:
The VisualStateManager enables you to specify states for a control, the appearance of a control when it is in a certain state, and when a control changes states.
His goal - is to define the application state, and each state to do an action, such as an animation. In this situation Binding is not used as such.
When use data binding framework, it seems not easy.
I do not think it's disadvantage. Data Binding needed as you mentioned: separate UI and Data completely. In fact, the whole MVVM pattern is based on a powerful technology as Data Binding. This feature allows you to create an abstract connection between Model and View via ViewModel. And the key word is Data, everywhere where there is work with the data, it is better to use Data Binding.
Binding allows you to do many interesting things, such as Validation, Converters and much more. It is typically used for Binding properties, and nothing more. To work with the UI using other features like VisualStateManager, Triggers, DataTriggers, etc. and it is not difficult when you use it to its destination, just need to get used to.
The only downside - is that Binding can be used for other purposes, such as use of the Converter when you can not do without it. And yes, at first it may seem unusual, but I do not think that this a drawback, the same can be said about other technologies.
Even as a drawback can be said about the performance. If you assign a value directly or via Binding, assigning a value directly will be faster. But I think that the advantages of Bindings allow not pay much attention to it.

Whats so bad about binding your View to Property of a Model and NOT ViewModel?

I often hear a Model must be wrapped by a ViewModel that the View is not coupled to the Model/not aware of it.
With MVC it is common to bind the View to the Model... nobody complains so what ?
I am frightened of creating all that wrappers and doing nearly only duplicating property stuff.
In some cases you don't need to, just as you don't need properties in many cases but can get away with public fields.
But your model should mirror the domain structure and logic, while a view model mirrors the UI structure and logic. At least, as far as I understood it. Those two are not necessarily the same and each one can change independently from the other.
You should always apply a pattern to your individual problem, and modify it in areas where it does not apply. Just because the pattern implies the usage of a view-model, doesn't mean you necessarily need a view-model in every scenario. In the case that your model exposes all of the needed properties and no further abstraction is needed, maybe a view-model is unnecessary.
However, in many cases the view-model will eventually be of great use and far easier to maintain than adding extra properties to the model. Consider this carefully before binding directly to the model.
The ViewModel is used to only pass the data that you really need to a view.
When you use the model, instead of the viewmodel it is possible that you use data that came directly from the database.
When using the model the wrong way, it is possible to edit data in the database that you don't want to edit.
It is safer to use a ViewModel.
One point which didn't seem to come up (directly) yet is that ViewModel can easily support data that should never even be in the model such as the text typed in the search text box or selected list items in case these values are needed in commands or further data bindings and passing them as parameters every time seems like too much trouble.
But as stated already, if you are confident that all the data you need is already available in the Model, go ahead and do away with the ViewModel.
One common scenario where ViewModels come in very handy is when Enum values should be displayed. In my eyes, a ViewModel is the perfect place to convert Enum values to user-friendly representations. You could even introduce a localization step in your ViewModel.
Furthermore, ViewModels can simplify some other scenarios. However, as you said, they can also duplicate a lot of code. That said, you could create a ViewModel with a Model property which allows to bind directly to the properties of the Model class. Now if you later realize that you need some conversion step, you can still add that property to the ViewModel and bind to that property.
But I think in most cases it makes sense to use a ViewModel from the beginning because it might be hard to introduce it in a later development stage.
There is no problem binding directly to a Model from your View where possible.
What you will find though is very quickly you run into a situation where you need to model things your view needs that aren't in your Model.
Given you never want to corrupt your Model with View concerns, you are left with no choice but to create a ViewModel.
It depends on may indicators: e.g. if your model is provided by EF there's no point in exposing it to your View - why the heck the View would need all model's method/properties and tons of stuff (not mentioning data security) But if your model is really simple and you feel, that you're not going to expand/change it much by and VM, there's nothing on the way to use it just like that :)
You might as well ask, "What's wrong with putting all the functionality of my program into one giant class?" On the one hand, there's nothing wrong; it can be made to work. On the other hand, everything is wrong: if your program is one big ball of wire, you have to straighten all of it out in order to change any of it.
Look at a Windows Forms programmer written by a beginner. You'll find all of the business logic in the buttons' Click event handlers. What's wrong with that? Don't you want that logic to be executed when the user clicks the button?
This is essentially what you're proposing doing within the world of WPF. Will it work? Sure. For trivial projects, it may even work well. You're accumulating technical debt, though, and when the time comes, you'll have to pay it off by refactoring your code into something manageable.

WPF UI element naming conventions

Although Hungarian notation is considered bad practice nowadays, it is still quite common to encode the type in the name of user interface elements, either by using a prefix (lblTitle, txtFirstName, ...) or a suffix (TitleLabel, FirstNameTextBox, ...).
In my company, we also do this, since it makes code written by co-workers (or by yourself a long time ago) easier to read (in my experience). The argument usually raised against doing this -- you have to change the name of the variable if the type changes -- is not very strong, since changing the type of a UI element usually requires rewriting all parts of the code were it is referenced anyway.
So, I'm thinking about keeping this practice when starting with WPF development (hmmm... should we use the txt prefix for TextBlocks or TextBoxes?). Is there any big disadvantage that I have missed? This is your chance to say "Don't do this, because ...".
EDIT: I know that with databinding the need to name UI elements decreases. Nevertheless, it's necessary sometimes, e.g. when developing custom controls...
Personally, I find that WPF changes the rules when it comes to this. Often, you can get away with little or no code behind, so having the prefixes to distinguish names makes things more confusing instead of less confusing.
In Windows Forms, every control was referenced by name in code. With a large UI, the semi-hungarian notation was useful - it was easier to distinguish what you were working with.
In WPF, though, it's a rare control that needs a name. When you do have to access a control via code, it's often best to use attached properties or behaviors to do so, in which case you're never dealing with more than a single control. If you're working in the UserControl or Window code-behind, I'd just use "Title" and "Name" instead of "txtTitle", especially since now you'll probably only be dealing with a few, limited controls, instead of all of them.
Even custom controls shouldn't need names, in most cases. You'll want templated names following convention (ie: PART_Name), but not actual x:Name elements for your UIs...
In my experience - In WPF when you change the type of a control, you normally do not have to rewrite any code unless you did something wrong. In fact, most of the time you do not reference the controls in code. Yes, you end up doing it, but the majority of references to a UI element in WPF is by other elements in the same XAML.
And personally, I find "lblTitle, lblCompany, txtFirstName" harder to read than "Title". I don't have .intWidth and .intHeight (goodbye lpzstrName!). Why have .lblFirstName? I can understand TitleField or TitleInput or whatever a lot more as it's descriptive of the what, not the how.
For me, wishing to have that type of separation normally means my UI code is trying to do too much - of course it's dealing with a UI element, it's in the window code! If I'm not dealing with code around a UI element, why in the world would I be coding it here?
Even from a Winforms perspective I dislike semi-hungarian.
The biggest disadvantage in my opinion, and I've written a LOT of ui code is that hungarian makes bugs harder to spot. The compiler will generally pick it up if you try to change the checked property on a textbox, but it won't pick up something like:
lblSomeThing.Visible = someControlsVisible;
txtWhatThing.Visible = someControlsVisible;
pbSomeThing.Visible = someControlsVisible;
I find it MUCH easier to debug:
someThingLabel.Visible = someControlsVisible;
whatThingTextBox.Visible = someControlsVisible;
someThingPictureBox.Visible = someControlsVisible;
I also think it's far better to group an addCommentsButton with an addCommentsTextBox than to group a btnAddComments with a btnCloseWindow. When are you ever going to use the last two together?
As far as finding the control I want, I agree with Philip Rieck. I often want to deal with all the controls that relate to a particular logical concept (like title, or add comments). I pretty much never want to find just any or all text boxes that happens to be on this control.
It's possibly irrelevant in WPF, but I think hungarian should be avoided at all times.
I like using a convention (just a good idea in general), but for UI stuff I like it to have the type of the control at the front, followed by the descriptive name -- LabelSummary, TextSummary, CheckboxIsValid, etc.
It sounds minor, but the main reason for putting the type first is that they'll appear together in the Intellisense list -- all the labels together, checkboxes, and so on.
Agree with the other answers that it's mainly personal preference, and most important is just to be consistent.
On the need for naming at all, given the prevalence of data binding... one thing you might want to consider is if your UI is ever subjected to automated testing. Something like QTP finds the visual elements in an application by Name, and so an automation engineer writing test scripts will greatly appreciate when things like tabs, buttons etc. (any interactive control) are all well named.
In WPF you practically never need (or even want) to name your controls. So if you're using WPF best practices it won't matter what you would name your controls if you had a reason to name them.
On those rare occasions where you actually do want to give a control a name (for example for an ElementName= or TargetName= reference), I prefer to pick a name describing based on the purpose for the name, for example:
<Border x:Name="hilightArea" ...>
...
<DataTrigger>
...
<Setter TargetName="hilightArea" ...
I prefix any user-interface name with two underscores, as in __ so it is sorted before other properties when debugging. When I need to use IntelliSense to find a control, I just type __ and a list of controls displays. This continues the naming convention of prefixing a single underscore to module level variables, as in int _id;.
You can use the official Microsoft website for Visual Basic 6 control naming conventions, and perhaps combine it with the recommended C# naming conventions. It's very specific, is widely used by developers in C# as well for control names, and can still be used in a WPF or Windows Forms context.
Visual Basic 6 control naming conventions: Object Naming Conventions
C# recommended naming conventions in general: General Naming Conventions

Do you databind your object fields to your form controls?

Or do you populate your form controls manually by a method?
Is either considered a best practice?
Generally, if data binding business or DAL objects is possible, I would use it. The old axiom holds true: The most error-free and reliable line of code is often the one you didn't have to write. (Bear in mind, however, that you need to know exactly how that data binding occurs, what its overhead is, and you have to be able to trust the framework and your source objects to be error-free!)
You would, as others have mentioned, manually populate if you needed specific functionality not brought to bear directly by binding, or if there is an issue with data binding business/DAL objects (as occasionally happens with certain 3rd-party controls).
Well, it depends. I have tended to use databinding wherever I could - it is darn convenient, but on occasion, I'll populate them manually. Particularly, I find it useful with controls like the DataGridView to use databinding. It makes filtering quite simple.
It really depends from what you are trying to achieve.
Databinding is simple and powerful, but if you need more control or some kind of side effect, you can manually populate control from a method.
Personally, I start with a databinding first, than change it later if it is necessary.

Resources