淘汰赛popover模板

时间:2018-03-27 11:00:54

标签: twitter-bootstrap knockout.js popover

如何在弹出模板中获取用户名?

<script type="html/text" id="editTemplate">

用户:

在这里小提琴:http://jsfiddle.net/gm79cr22/64/

由于

1 个答案:

答案 0 :(得分:1)

解决这个问题最简单的方法是使用jQuery直接创建并获取popover dom节点,这样你就可以用它来绑定它。

var ViewModel = function() {
  self = this;
  self.exampleText = ko.observable("Click me!");

  var data = [{
      name: "User1",
      date: "01/01/2017"
    },
    {
      name: "User2",
      date: "01/01/2017"
    },
    {
      name: "User3",
      date: "01/01/2017"
    },
    {
      name: "User4",
      date: "01/01/2017"
    }
  ];

  self.users = ko.observableArray(data);

};

ko.bindingHandlers.popover = {
  init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
    var cssSelectorForPopoverTemplate = ko.utils.unwrapObservable(valueAccessor());
    var popOverTemplate = $("<div class='my-knockout-popver'>" + $(cssSelectorForPopoverTemplate).html() + "</div>");

    $(element).popover({
      content: popOverTemplate,
      html: true,
      trigger: 'hover'
    });

    ko.applyBindings(viewModel, popOverTemplate[0]);
  },
};

ko.applyBindings(new ViewModel());
@import url('https://maxcdn.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.no-icons.min.css');
/*.example-container{
    float: right;
    margin-top: 10px;
    
    font-size:24px;
}*/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.1.0/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<table class="table">
  <thead>
    <tr>
      <th>Name</th>
      <th>Status</th>
      <th>Date</th>
    </tr>
  </thead>
  <tbody data-bind="foreach: users ">
    <td data-bind="text: name"></td>
    <td>
      <div data-placement="top" data-title="Info" data-bind="popover: '#editTemplate'">
        <i class="fa fa-adjust" aria-hidden="true"></i>
        <!-- This is the popover template  -->
        <script type="text/html" id="editTemplate">
          User: <span data-bind="text: name"></span>
        </script>
      </div>
    </td>
    <td data-bind="text: date"></td>
  </tbody>
</table>