Knockout.js: conditionally link title div attribute

I have a viewModel on my page that contains data to review the current states of some devices. So far, everything is working fine, except for one problem: I need to set the title attribute of the div element depending on a different value in my view model.

I know that you can basically set the title attribute like this (in the data binding attribute of the div tag):

attr: { title: 'Some title' } 

Using the above statement, "Some title" is set as a hint when the div hangs. I can also install this:

 attr: { title: ConnectState.Value() } 

and prints the correct value (integer value) of my current viewModel data, so the viewModel is populated correctly.

Now I need to change this to something like this:

 attr: { title: { 'Text 1': ConnectState.Value() == 0, 'Text 2': ConnectState.Value() == 1, 'Text 3': ConnectState.Value() == 2, 'Text 4': ConnectState.Value() == 3 } } 

In the above example, "[object Object]" will be displayed as a title (for example, as a tooltip). How can i fix this? Thank you very much in advance!

+7
source share
2 answers

Define ko.computed in your view model.

 self.ConnectTitle = ko.computed(function() { return 'Text ' + (self.ConnectState.Value() + 1).toString(); }); 

Then: -

 attr: { title: ConnectTitle } 

How is your binding. You can replace the contents of a computable function with something that suits your needs if your text were a simple example.

+9
source

You can use the ternary operator, something like this:

 attr: { title: ConnectState.Value() == 0 ? 'Text 1' : ConnectState.Value() == 1 ? 'Text 2' : ConnectState.Value() == 2 ? 'Text 3' : 'Text 4' } 
+2
source

All Articles