Knockout - applying styles to the selected item in a Bootstrap Select - javascript

So this is piling libraries on top of libraries, but I'm not sure what else to do.
Our application has a number of drop-down elements all of which are Bootstrap Select objects. These replace the standard set of option tags inside the select with a complex series of other elements that give you much greater control over the styling of the children and make them searchable.
Most of these objects exist as reusable components with an HTML view and a Typescript ViewModel, bound together with Knockout.
A number of these menus have icons next to the text. This is handled with optionsAfterRender. Here's an example.
View:
<select
data-bind="options: items,
value: selectedValue,
optionsText: 'value',
optionsValue: 'id',
selectPicker: {},
optionsAfterRender: applyOptionAttributes">
</select>
ViewModel:
export default class SelectComponent {
selectedValue: KnockoutObservable<string>;
items: KnockoutObservableArray<SelectOption>
constructor(koObservable: KnockoutObservable<string>) {
// items fetched and bound
}
applyOptionAttributes(option: Node, item: SelectOption): void {
ko.applyBindingsToNode(option, { attr: { "data-content": `<img src="${item.iconurl}" />`, title: item.value } }, item);
}
}
interface SelectOption {
value: string;
id: string
iconurl: string;
}
And this is fine. However, because of the way Bootstrap Select styles the items inside it, the icon is not applied to the currently selected item - it's only displayed when the user clicks on the menu and it pops up.
Now, of course, we have a requirement to display the icon in currently selected item too. But I don't know how to get that element to bind to it. I can't fetch it directly because of the view-viewmodel pattern. It doesn't seem to be among the nodes passed by optionsAfterRender.
How can I get hold of it to style it?
EDIT: pretty sure this is a bug in bootstrap-select. Have raised an issue
https://github.com/snapappointments/bootstrap-select/issues/2129

You could try to fix this by preventing the post-processing of the options:
Replace the options binding with a foreach binding in the select element, binding each option with the appropriate ko-bindings.
Make sure the selectPicker binding has its descendant bindings bound before calling selectpicker on the element.
Profit!
ko.bindingHandlers['selectPicker'] = {
init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
ko.applyBindingsToDescendants(bindingContext, element);
$(element).selectpicker();
return { controlsDescendantBindings: true };
}
}
ko.applyBindings({
selectedValue: ko.observable(3),
options: [
{ id: 1, name: 'Mustard', dc: '<span class="badge badge-warning">Mustard</span>' },
{ id: 3, name: 'Ketchup', dc: '<span class="badge badge-danger">Ketchup</span>' },
{ id: 4, name: 'Relish', dc: '<span class="badge badge-success">Relish</span>' }
]
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.3/css/bootstrap-select.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.3/js/bootstrap-select.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<select data-bind="selectPicker, value: selectedValue">
<!-- ko foreach: options -->
<option data-bind="text: name, attr: { value: id, 'data-content': dc }"></option>
<!-- /ko -->
</select>

Related

on Change event in select with knockout

I have a problem how to call onchanges knock js to my select option, i already have a function and html, but when i choose the select option, nothing changes
<select data-bind="event:{change:setSelectedStation() },
options: seedData,
optionsText: 'text',
optionsValue: 'value'">
</select>
here is my function
setSelectedStation: function(element, KioskId){
this.getPopUp().closeModal();
$('.selected-station').html(element);
$('[name="popstation_detail"]').val(element);
$('[name="popstation_address"]').val(KioskId);
$('[name="popstation_text"]').val(element);
// console.log($('[name="popstation_text"]').val());
this.isSelectedStationVisible(true);
},
Use knockout's two-way data-binds instead of manually subscribing to UI events.
Knockout's value data-bind listens to UI changes and automatically keeps track of the latest value for you.
Instead of replacing HTML via jQuery methods, you use text, attr and other value bindings to update the UI whenever your selection changes.
If you want to perform additional work when a selection changes (e.g. closing a pop up), you subscribe to the selected value.
var VM = function() {
this.seedData = [
{
text: "Item 1",
data: "Some other stuff"
},
{
text: "Item 2",
data: "Something else"
},
{
text: "Item 3",
data: "Another thing"
}
];
this.selectedItem = ko.observable();
this.selectedItem.subscribe(function(latest) {
console.log("Input changed");
}, this);
};
ko.applyBindings(new VM());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<select data-bind="
value: selectedItem,
options: seedData,
optionsText: 'text'">
</select>
<!-- ko with: selectedItem -->
<p>
Your selection: <span data-bind="text: data"></span>
</p>
<!-- /ko -->

Get selected text on dropdown change event in Knockout.js

I am trying to get the text of selected index in dropdown using knockout.js,
following is my HTML
<select name="" id="management" class="form-control" data-bind="value: ManagementCompanies,optionText:ManagementCompaniestxt">
<option value="0">---Select---</option>
<option value="1">abcd</option>
<option value="2">efgh</option>
</select>
following is my Model binding:
var FilterViewModel = {
ManagementCompanies: ko.observable(''),
ManagementCompaniestxt:ko.observable('')
}
FilterViewModel.ManagementCompanies.subscribe(function (newValue) {
alert(FilterViewModel.ManagementCompaniestxt());
});
ko.applyBindings(FilterViewModel, window.document.getElementById("SelectFilters"));
i have tried to bind using Text as well but didn't work.
how can i get selected text abcd in subscribe event?
thanks
It's a bit weird that you're trying to get data from your view to your viewmodel. Usually, your view is a representation of your viewmodel. It's better to have the data needed to render your <select> in your model, and use knockout's options data-bind to render it.
Here's how you can do this:
var FilterViewModel = {
ManagementCompanies: ko.observable(''),
ManagementCompaniestxt: ko.observable(''),
options: [
{ text: "---Select---", value: 0 },
{ text: "abcd", value: 1 },
{ text: "efgh", value: 2 }]
}
FilterViewModel.ManagementCompanies.subscribe(function(newValue) {
console.log(newValue.text);
});
ko.applyBindings(FilterViewModel);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<select data-bind="value: ManagementCompanies,
options:options,
optionsText: 'text'">
</select>

What is the ko.observable actually doing in this situation?

So what exactly is the ko.observable() doing? Here's the situation. I have a boolean ko.observable(), as you can see. I have click set to that value, so it SHOULD toggle the value of the true false contained within it's method call.
When I watch the array get populated in the developer tools, I see that selected does not = true or false, it instead = a pretty extensive function, and I can't find the true or false value anywhere inside of that, so I have no idea what exactly is happening when ko.observable() is used
What I expected is for tab.selected to be the value of tabArray[tab].selected, and when the page loads, that is correct. However, after clicking, tabArray[tab].selected = [Object object] when the text value is written out. I attempt to use:
<pre data-bind="text: JSON.stringify(ko.toJS(tab.selected)"></pre>
(found here: http://www.knockmeout.net/2013/06/knockout-debugging-strategies-plugin.html) and that prints out either true or false, do I need to do this for the other places where i need that value? Because I'm not sure exactly what ko.observable is doing.
define(['knockout', 'text!../Content/SSB/PartialViews/MainContent.html'], function (ko, MCTemplate) {
ko.components.register('MainContent', {
template: MCTemplate
});
var MainViewModel = {
tabArray: [
{ name: 'bob', selected: ko.observable(true) },
{ name: 'bib', selected: ko.observable(false) },
{ name: 'bab', selected: ko.observable(false) },
{ name: 'bub', selected: ko.observable(false) },
{ name: 'beb', selected: ko.observable(false) },
]
};
ko.applyBindings(MainViewModel);
return {
viewModel: MainViewModel
}
});
the HTML
<div id="tab">
<ul class="nav nav-tabs" role="tablist">
<!--ko foreach: {data: $parent.tabArray, as: 'tab'}-->
<li data-bind="click: tab.selected, css: { 'active': tab.selected}">
<a data-bind="attr: {href: '#' + tab.name}, text: name"></a>
<div data-bind="text: tab.name"></div>
<div data-bind="text: tab.selected"></div>
</li>
<!--/ko-->
</ul>
<!--ko foreach: {data: $parent.tabArray, as: 'tab'}-->
<div class="ui-tabpanel" role="tabpanel" data-bind="visible: tab.selected">
<p data-bind="text: name"></p>
</div>
<!--/ko-->
</div>
The click binding calls the provided function, passing it the current view model (also called $data). That's why you see [Object object] as the observable's value after the click. Since you want the click to toggle the observable, you need to create a function to do that. A nice, clean way to do this is through a custom binding, which I'll call toggle:
ko.bindingHandlers.toggle = {
init: function(element, valueAccessor) {
ko.utils.registerEventHandler(element, 'click', function () {
var obs = valueAccessor();
obs(!obs());
});
}
};
Now you bind using toggle instead of click: <li data-bind="toggle: tab.selected...

ng-repeat controller and parent update

I've been reading a lot on angular scopes and inheritance but I can't get my head around this problem. Here is the HTML I'm using:
<div class="sensorquery-sensor" ng-repeat="sensor in query.sensors" ng-controller="SensorsCtrl">
<select class="form-control"
ng-model="selected.sensor"
ng-options="sensor.name for sensor in parameters.sensors">
</select>
<select class="form-control"
ng-model="selected.definition"
ng-options="definition.value for definition in definitions">
</select>
<select class="form-control"
ng-model="selected.operation"
ng-options="operation for operation in operations">
</select>
</div>
As you can see, I have an ng-repeat based on query.sensors. The values stored in this query.sensors array should be simple:
{
name: 'sensor1',
type: 'temperature'
}
But I want to use a child controller: SensorsCtrl to handle more logic per sensor and hide the complexitiy of sensors. A sensor can look like:
{
name: 'sensor1',
attributes: [
'model',
'brand'
],
definitions: [
{
datatype: 'double',
value: 'temperature'
},
{
datatype: 'integer',
value: 'pressure'
},
{
datatype: 'string',
value: 'color'
}
]
}
So it's in my SensorsCtrl controller where I want to put the selection logic:
$scope.$watch('selected.sensor', function(sensor) {
$scope.definitions = sensor.template.definition;
});
$scope.$watch('selected.definition', function(definition) {
if (definition.datatype === 'string') {
$scope.operations = ['Count'];
} else {
$scope.operations = ['Max', 'Min'];
}
$scope.selected.operation = _.first($scope.operations);
});
How do I keep the link with the parent query.sensors[$index] while transforming the sensor as the user selects different sensors and definitions?
Setting up a watcher on selected and updating the query.sensors array triggers an infinite $digest loop.
I found the solution which was right before my eyes:
<div class="sensorquery-sensor" ng-repeat="sensor in query.sensors" ng-controller="SensorsCtrl">
<!-- ... -->
</div>
The sensor is a reference to the original object of the parent query.sensors. An it's created in the scope of the sub-controller.
So in my SensorsCtrl controller, I can just watch:
$scope.$watch('sensor.definition', function(definition) {
/* ... */
});
So I can put hide some complexity in this controller while maintaining a proper link to the original element.
It does not answer the question of maintaining a less complex object but it's a different question I guess.

KnockoutJs: Getting value from dropdownlist

I'm having hard time getting the selected value of dropdown list using Knockout JS
jsFiddle
HTML
<select id="l" data-bind="options: locations, value=selectedLocation"></select>
<select id="j" data-bind="options: jobTypes, value=selectedJobType"></select>
<button data-bind="click: myFunction"> Display </button>
Script
var viewModel = {
locations: ko.observableArray(['All Locations', 'Sydney', 'Melbourne', 'Brisbane', 'Darwin', 'Perth', 'Adelaide']),
selectedLocation: ko.observable(),
jobTypes: ko.observableArray(['All Vacancies', 'Administration', 'Engineering', 'Legal', 'Sales', 'Accounting']),
selectedJobType: ko.observable(),
myFunction: function() {
alert(selectedJobType + ' ' +selectedLocation );
}
};
// ... then later ...
//viewModel.availableCountries.push('China');
// Adds another option
ko.applyBindings(viewModel);
That should be
value:selectedLocation
and:
value:selectedJobType
in you bindings. Bindings use the same syntax as an object literal.
Also, in your alert, you need viewModel.selectedJobType(), because (a) it's a property of viewModel not of global and (b) it's an observable so you need to call it to get the value. Same for selectedLocation.
Here's a working fiddle

Categories

Resources