Knockout.js: conditionally bind title attribute of div
Solution 1
Define a ko.computed in your viewmodel.
self.ConnectTitle = ko.computed(function() {
return 'Text ' + (self.ConnectState.Value() + 1).toString();
});
Then:-
attr: { title: ConnectTitle }
As your binding. You can replace the contents of the computed's function with something that'll suit your needs, if your text was just a simple example.
Solution 2
You can use ternary operator, something like this:
attr: {
title: ConnectState.Value() == 0 ? 'Text 1' :
ConnectState.Value() == 1 ? 'Text 2' :
ConnectState.Value() == 2 ? 'Text 3' :
'Text 4'
}
Related videos on Youtube
Rob
"I love deadlines. I like the whooshing sound they make as they fly by." Douglas Adams
Updated on September 16, 2022Comments
-
Rob about 1 year
I have a viewModel on my page that holds the data for an overview of current states of some devices. So far everything works great except for one issue: I need to set the title attribute of a div element depending on another value in my viewModel.
I know that you can basically set the title attribute like this (within the data-bind attribute of the div tag):
attr: { title: 'Some title' }
Using the statement above, "Some title" gets set as tooltip when hovering the div. I can also set this:
attr: { title: ConnectState.Value() }
and it outputs the correct value (an integer value) of my current viewModel data, so the viewModel gets populated correctly.
Now I need to change this to something like that:
attr: { title: { 'Text 1': ConnectState.Value() == 0, 'Text 2': ConnectState.Value() == 1, 'Text 3': ConnectState.Value() == 2, 'Text 4': ConnectState.Value() == 3 } }
The example above will only give "[object Object]" as title (resp. as tooltip). How can I fix that? Thanks a lot in advance!
-
nemesvWhy don't you write
attr: { title: 'Text ' + (ConnectState.Value() + 1) }
Or your actual text is more complicated than your example?
-
-
Rob over 10 yearsThanks for your suggestion. The title attribute I need to set exists in a data-bound table row: <tbody data-bind="foreach: Rows"> So I have to apply this ConnectTitle function to every item in my viewModels "Rows" collection, which is dynamically, depending on the page. I couldn't figure out how to achieve that.
-
Paul Alan Taylor over 10 yearsEach of your rows is represented by an object, correct? Post your Javascript view model and we'll take a look.
-
Rob almost 4 yearsThat's elegant! Never used a ternary like this.