[英]How do you filter the content collection of an ArrayController in Ember.js using a checkbox in a view?
我正在為Ember和Ember-Data使用最新代碼。 我將Rails作為提供JSON的后端,效果很好。 我希望能夠使用視圖中的復選框對Ember模型的“活動”屬性進行過濾。 我希望該復選框僅在選中該復選框時顯示active = true的數據。 我不想從陣列中刪除數據,只希望隱藏數據。 這是我目前所擁有的,但無法正常工作。
模型:
App.Org = DS.Model.extend({
code: DS.attr('string', { defaultValue: 'N/A' }),
name: DS.attr('string', { defaultValue: 'N/A' }),
source: DS.attr('string', { defaultValue: 'N/A' }),
status: DS.attr('string', { defaultValue: 'N/A' }),
type: DS.attr('string', { defaultValue: 'N/A' }),
note: DS.attr('string', { defaultValue: 'N/A' }),
financial_Flag: DS.attr('string', { defaultValue: 'N/A' }),
expense_Flag: DS.attr('string', { defaultValue: 'N/A' }),
revenue_Flag: DS.attr('string', { defaultValue: 'N/A' }),
created_At: DS.attr('string', { defaultValue: 'N/A' }),
updated_At: DS.attr('string', { defaultValue: 'N/A' }),
active: function() {
var status = this.get('status');
var active = (status === 0) ? false : true;
console.log("status: " + status + " | active: " + active);
return active;
}.property('status')
}).reopenClass({
collectionUrl: '/orgs',
resourceUrl: '/orgs/%@',
resourceName: 'org'
});
ArrayController:
App.OrgsController = Em.ArrayController.extend({
isEmpty: function() {
console.log("############ App.OrgsController.isEmpty called");
return this.get('length') === 0;
}.property('length'),
toggleActive: function(){
console.log("############ App.OrgsController.isActive called");
return this.filterProperty('active', value).forEach(this.removeObject, this);
}.property('@each.active'),
init: function() {
this.set('content', App.store.findAll(App.Org));
},
refreshOrgs: function() {
this.set('content', App.store.findAll(App.Org));
},
getInactiveOrgs: function(){
this.set('content', App.store.find(App.Org, {status: "0"}));
}
});
在我看來,我有:
<label>
isActive
{{view Ember.Checkbox checkedBinding="App.OrgsController.toggleActive" disabledBinding="App.OrgsController.isEmpty" }}
</label>
這可以通過創建一個計算屬性來實現,該屬性基於復選框的布爾值返回整個集合或僅返回項的子集。 例如,
App.Post = DS.Model.extend({
text: DS.attr('string'),
active: DS.attr('boolean')
});
App.IndexRoute = Ember.Route.extend({
model: function() {
return App.Post.find();
}
});
App.IndexController = Ember.ArrayController.extend({
hideInactive: false,
filteredContent: function() {
var content = this.get('content');
if (!content || !this.get('hideInactive'))
return content;
return content.filter(function(item) {
return item.get('active');
});
}.property('content.isLoaded', 'hideInactive')
});
您的模板應如下所示:
<script type="text/x-handlebars" data-template-name="index">
<p>{{view Ember.Checkbox checkedBinding="hideInactive"}} Hide Inactive Posts</p>
<br/>
{{#each filteredContent}}
<p>{{text}}</p>
{{/each}}
</script>
如果將active
定義為計算屬性,這也將起作用,如您的示例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.