Reputation: 5113
I have a case here
I have an observable array, and i have a single component, which is to vouch for the presence of a value in the given observable array and change the css if it exists so.
for ex in this script i am to check, if the word "hello" exists in the array and if it does than change the css to blue
SCRIPT
function VM() {
var arrInterests = 'hello,world'.split(',');
this.interests = ko.observableArray(arrInterests);
};
ko.applyBindings((new VM()));
HTML
<p class="green" data-bind="css: { 'blue': interests() === 'hello'}">Hello exists:
</p>
CSS
.green {
background-color: green;
border:2px solid red;
}
.blue {
background-color: blue;
border:2px solid red;
}
Upvotes: 0
Views: 186
Reputation: 47968
You should use Array.indexOf
to search for a value within arrays:
interests().indexOf('hello') >= 0
Of course, you should put this code in a computed property inside of the viewmodel:
function VM() {
var arrInterests = 'hello,world'.split(',');
this.interests = ko.observableArray(arrInterests);
this.contains = function(value) {
return ko.computed(function() {
return this.interests().indexOf(value) >= 0;
});
};
};
// usage
<p class="green" data-bind="css: { 'blue': contains('hello') }">Hello exists:</p>
<p class="green" data-bind="css: { 'red': contains('world') }">world exists:</p>
....
Upvotes: 1