Skip to content

Instantly share code, notes, and snippets.

@Sharp6
Created March 20, 2017 19:49
Show Gist options
  • Save Sharp6/a61f83f3a9967a1659a88af52fb00fe7 to your computer and use it in GitHub Desktop.
Save Sharp6/a61f83f3a9967a1659a88af52fb00fe7 to your computer and use it in GitHub Desktop.
Binding ko observables to a bootstrap modal
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<div class="container">
<table class="table">
<thead>
<tr><th>Name</th><th>Details</th>
</thead>
<tbody data-bind="foreach:stocks">
<tr>
<td data-bind="text:name"></td>
<td><a data-toggle="modal" data-target="#myModal" data-bind="click:$parent.selectedStock">show details</a></td>
</tr>
</tbody>
</table>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document" data-bind="with:selectedStock">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
<h4 class="modal-title" id="myModalLabel" data-bind="text:name">Modal title</h4>
</div>
<div class="modal-body">
Number of stocks: <span data-bind="text: numberOfStocks"></span> (<span data-bind="text:shortname"></span>)
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
</div><!-- /.container -->
<script type='text/javascript' src='https://code.jquery.com/jquery-3.2.0.min.js'></script>
<script type='text/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.1/knockout-min.js'></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script type="text/javascript">
var viewModel = {
selectedStock: ko.observable(),
stocks: ko.observableArray([
{
name: "facebook",
shortname: "fb",
numberOfStocks: 3
},
{
name: "twitter",
shortname: "tw",
numberOfStocks: 42
}
]) // Initially blank
};
ko.applyBindings(viewModel);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment