This binding provides generic ways set values on DOM elements.
href of a tag, src of img, title of element, also can bind custom attribute but little different approach.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<html> <head> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.5.1/knockout-latest.js"></script> </head> <body> <a data-bind="attr: { title: modalTitle, href: modalUrl, target: '_blank'}">Visit Us</a> <script type="text/javascript"> var viewModel = { modalUrl: ko.observable('https://www.coffeewithmagento.in/'), modalTitle: ko.observable('Coffee With Magento') }; ko.applyBindings(viewModel); </script> </body> </html> |
We binds title , href and target to <a/> tag.
Now let’s check on custom attributes binding such as data-custom or data-something.
We can not bind custom attributes not same we do with native attributes.
Below code does not work with custom attributes. Why?
Because data-custom or data-something is not legal identifier for javascript.
1 |
<div data-bind="attr: { data-custom: customValue }"></div> |
Solution is simple , just wrap identifier name in quotes just as below.
1 |
<div data-bind="attr: { 'data-custom': someCustomValue }">Check value by inpect element</div> |