我正在尝试使用 Ember-CLI 实现以下目标:
加载初始项目列表后,用户可以从下拉列表中选择一个城市,以仅查看他/她感兴趣的项目。就我而言,这是城市中的地区。您可以从下拉列表中选择要查看的城市只有该城市的地区。
理想情况下,所有操作都应该在不单独调用 (单击时)的情况下发生。
到目前为止,我已经有了这个,但是"filteredContent"的控制台.log返回一个包含 0 个元素的数组。有什么暗示我做错了什么吗?
地区/索引.hbs:
<p>{{view "select" content=cities optionValuePath="content.id" optionLabelPath="content.name" selection=selectedCity}}</p>
{{#each item in filteredContent}}
<p>{{item.name}} in {{item.city.name}}</p>
{{/each}}
路线:
var DistrictListRoute = Ember.Route.extend({
model: function () {
return this.store.find('district');
},
setupController: function(controller, model) {
this._super(controller, model);
this.store.find('city').then(function(cities) {
controller.set('cities', cities);
});
}
});
export default DistrictListRoute;
控制器:
export default Ember.Controller.extend({
filteredContent: [],
selectedCity: null,
selectedCityChanged: function () {
var selectedCity = this.get('selectedCity');
console.log(selectedCity);
var filteredContent = this.get('model').filterBy('city', selectedCity);
console.log(filteredContent);
}.observes('selectedCity')
});
型:
export default DS.Model.extend({
city: DS.belongsTo('city', {async: true}),
name: DS.attr('string'),
advert: DS.hasMany('item')
});
终于想通了:
控制器:
export default Ember.ArrayController.extend({
selectedCity: null,
filteredContent: [],
selectedCityChanged: function () {
var selectedCity = this.get('selectedCity');
var filteredContent = this.get('model').filterBy('city.id', selectedCity.id);
this.set('filteredContent', filteredContent);
}.observes('selectedCity')
然后,车把模板需要一些调整:
<p>{{view "select" content=cities optionValuePath="content.id" optionLabelPath="content.name" selection=selectedCity}}</p>
{{#if filteredContent}}
<h2>District in {{selectedCity.name}}</h2>
{{#each district in filteredContent}}
<p>{{district.name}} in {{district.city.name}}</p>
{{/each}}
{{else}}
<h2>Districts</h2>
{{#each district in content}}
<p>{{district.name}} in {{district.city.name}}</p>
{{/each}}
{{/if}}