我正在尝试合并这个有效 示例 http://jsbin.com/AViZATE/37/edit我自己的项目的过滤搜索栏。搜索栏似乎没有连接到我的对象列表。 :(
让我告诉你我做了什么。
App.RecordCategoriesController = Ember.ArrayController.extend({
searchResult: function(){
var searchTerm = this.get('searchTerm');
var regExp = new RegExp(searchTerm,'i');
this.get('model').set('content',this.store.filter('recordCategory',function(item){
return regExp.test(item.get('categoryName'));
}));
}.observes('searchTerm'),
});
正如您在上面看到的,我已将“todo
”替换为“recordCategory
”,将“title
”替换为“”类别名称
'。到目前为止似乎还不错。”
在 record_categories.hbs 中,我创建了将用于过滤的输入栏。
{{input type="text" id="search-todo" placeholder="Search Todo List..." value=searchTerm}}
然后在它下面,#each Handlebars 循环显示我的列表
{{#each itemController="recordCategory"}}
<li>{{categoryName}}</li>
{{/each}}
我错过了什么吗?我注意到 searchResults 在他们的示例中似乎没有在其他任何地方调用
这也是我的路线,因为为什么不呢。
App.RecordCategoriesRoute = Ember.Route.extend({
model: function() {
VpcYeoman.RecordCategories.FIXTURES=[];
$.ajax({
url: '/recordCategories',
dataType: 'json',
type:"get",
async: false,
success : function(data, textStatus, xhr) {
if(xhr.status==200){
VpcYeoman.RecordCategories.FIXTURES=data;
}
}
});
return this.store.find('recordCategories');
}
});
最佳答案
我将尽量忽略 JSBin 并查看您拥有的内容,因为我认为这会对您有更多帮助。因此,如果我遗漏了 JSBin 中的一些明显内容,请告诉我。
首先要注意的是,从您的 route ,您返回了一个对象数组。 Ember 通常会为您生成一个 ArrayController
,但您已经自己扩展了它。 ArrayController
的特殊(和优点)在于它们的内容是数组。所以在你的模板中,你可以这样做:
{{#each}}
{{categoryName}}
{{/each}}
这将列出从 this.store.find('recordCategories')
返回的所有项目。
但是你想过滤你的项目,所以这不好。那么让我们继续第二点。过滤项目列表的最佳方法是使用只读计算属性。您肯定不想将模型的内容设置为过滤后的项目。您希望原始项目保持完整,而过滤器只是查看原始项目的某种方式。因此,使用来自 here 的稍作修改的示例,让我们这样做吧。
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')
});
现在您已经有了一个计算属性,可以根据搜索词过滤数组 Controller 中的项目。并且由于它的依赖性,它会在项目更改或搜索词更改时重新计算。这样,您不必更改任何模型值。最后,您将像这样使用它:
// record_categories.hbs
{{input type="text" id="search-todo" placeholder="Search Todo List..." value=searchTerm}}
{{#each searchResults}}
{{categoryName}}
{{/each}}
为了确保我没有完全胡扯,我创建了一个 JSBin以证明它有效。
关于javascript - Emberjs - 将 {{ input }} 过滤栏与我的对象列表连接起来。在我输入时,列表会过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22720183/