I have a html element which looks like this:
<div data-bind="attr: { 'data-text': hasText && textMessage }"></div>
Javascript
var viewModel = {
hasText: ko.observable(false),
textMessage: ko.observable()
};
What i want, is to dynamically add and remove the ‘data-text’ attribute and populate it with the value of textMessage property.
Right now, it outputs the boolean result of the hasText && textMessage:
<div data-text='0' />
or
<div data-text='1' />
How can I dynamically remove or add the attribute and populate it with the data?
You need to create a computed observable property and then bind that to your
data-textattribute:And then your binding will look like:
Demo JSFiddle.