基于observableArray使用optgroup构造敲除SELECT [英] Construct a knockout SELECT with optgroup based on observableArray

查看:53
本文介绍了基于observableArray使用optgroup构造敲除SELECT的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发了一个带有淘汰赛的项目.我找到了一种使用剔除绑定和optgroup进行选择的方法.解决方案如下: http://jsfiddle.net/HPhmB/3/

I develop a project with knockout. I found a way to have my select with knockout binding and optgroup. Here is the solution: http://jsfiddle.net/HPhmB/3/

不幸的是,此解决方案使用静态模型填充"option"和选择中的"optgroup".

Unfortunately this solution use a static model for populating 'option' & 'optgroup' in the select.

出于我个人的需要,我希望有更多动态.我想从数据库提供的observableArray开始.这个observableArray看起来像这样:

For my personal need, I would like something more dynamic. I would like to start with an observableArray provided from a database. This observableArray looks something like this:

var vehicles = ko.observableArray([
    {
     Id: 1,
     Brand: "Volkswagen",
     Type: "Golf"
    },
    {
     Id: 2,
     Brand: "Volkswagen",
     Type: "Sharan" 
    },
    {
     Id: 3,
     Brand: "BMW",
     Type: "118i"
    }
    {
     Id: 4,
     Brand: "BMW",
     Type: "525D"
    }
 ]);

我的问题:是否有可能基于此单个observableArray解决方案来构造选择.也许借助计算属性来检索optgroup/options?

My question: is it possible to have a solution based on this single observableArray to construct the select. Maybe with the help of computed properties to retrieve the optgroup/options?

谢谢.

推荐答案

此处是执行此操作的方法之一.这不是最佳方法,但效果很好:

Here is one of the ways to do this. It is not optimal but works well:

var ViewModel = function () {
    var self = this;
    self.vehicles = ko.observableArray([{
        Id: 1,
        Brand: "Volkswagen",
        Type: "Golf"
    }, {
        Id: 2,
        Brand: "Volkswagen",
        Type: "Sharan"
    }, {
        Id: 3,
        Brand: "BMW",
        Type: "118i"
    }, {
        Id: 2,
        Brand: "BMW",
        Type: "525D"
    }]);

    self.brands = ko.computed(function(){
        var list = ko.utils.arrayMap(self.vehicles(), function(item){
            return item.Brand;
        });

        return ko.utils.arrayGetDistinctValues(list);
    });
};

ko.applyBindings(new ViewModel());

<select data-bind="foreach: brands">
    <optgroup data-bind="attr: {label: $data}, foreach: $parent.vehicles">
    <!-- ko if: Brand == $parent -->
        <option data-bind="text: Type"></option>
    <!-- /ko -->
    </optgroup>
</select>

提琴: http://jsfiddle.net/HPhmB/55/

这篇关于基于observableArray使用optgroup构造敲除SELECT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆