0

I have an ko.observableArray that I want to apply a filter when displaying the result.

Here is my fiddle: Fiddle

var myViewModel = {
departments: ko.observableArray([{
        departmentname: 'IT'
    }, 
    {
        departmentname: 'Admin'
    }, 
    {
        departmentname: 'Technical'
    }, 
    {
        departmentname: 'Operations'
    }]),
filters: "IT"
};

As you can see from the fiddle the filter work if you filter for one value.

but I require to filter for more than one value eg.

filters: "IT","Admin" 

Is there a way to do this?

Thanks in advance

4

1 回答 1

0

I'd use a computed observable to provide a filtered array. I've changed your view model to be a function, as I was having problem with referencing other elements of the view model in the computed:

var myViewModel = function(){
    var self = this;
    self.departments = ko.observableArray([{
        departmentname: 'IT'
    }, {
        departmentname: 'Admin'
    }, {
        departmentname: 'Technical'
    }, {
        departmentname: 'Operations'
    }]);
    self.filters =  ko.observableArray(["IT", "Admin"]);
    self.filterdept = ko.computed(function () {
        var filteredArray = ko.utils.arrayFilter(self.departments(), function (department) {
            return self.filters().indexOf(department.departmentname) != -1;
        });

        return filteredArray;
    });
};

And then change the binding from a with to a foreach:

<div data-bind="foreach: filterdept()"> <span data-bind="text: departmentname"></span>

And change the binding to this:

var vm = new myViewModel();
ko.applyBindings(vm);

http://jsfiddle.net/manzanotti/X3LMR/6/

于 2013-02-26T10:17:51.060 回答