Emberjs - Connecting an {{ input }} filter bar with my list of Objects. As I type, the list filters

你离开我真会死。 提交于 2019-12-01 12:55:46

I'm going to try to mostly ignore the JSBin and look at what you have, as I think that will help you more. So if I miss something obvious from the JSBin, let me know.

First thing to notice is that, from your route, you return an array of objects. Ember would normally generate an ArrayController for you, but you've extended that yourself. And the thing that's special (and nice) about ArrayControllers is that their content is the array. So in your template, you could just do this:

{{#each}}
    {{categoryName}}
{{/each}}

And that would list all of the items that were returned from this.store.find('recordCategories').

But you want to filter your items, so that's no good. So let's move on to point two. The best way to filter a list of items is by using a read-only computed property. You definitely don't want to set the content of the model to the filtered items. You want the original items to remain intact, and the filter be just a certain way of looking at the original items. So, using a slightly modified example from here, let's do that.

App.RecordCategoriesController = Ember.ArrayController.extend({

    searchResults: function() {
        var searchTerm = this.get('searchTerm');
        var regExp = new RegExp(searchTerm,'i');

        // We use `this.filter` because the contents of `this` is an array of objects
        var filteredResults = this.filter(function(category) {
            return regExp.test(category.get('categoryName'));
        });

        return filteredResults;
    }.property('@each.categoryName', 'searchTerm')

});

So now you've got a computed property that filters the items in the array controller based on the search term. And because of its dependancies, it will re-caclulate anytime the items change or the search term changes. And this way, you didn't have to change any model values. Finally, you'd use it like this:

// record_categories.hbs

{{input type="text" id="search-todo" placeholder="Search Todo List..." value=searchTerm}}

{{#each searchResults}}
    {{categoryName}}
{{/each}}

And just to make sure that I wasn't completely BSing, I created a JSBin to show that it works.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!