[英]accessing another models data in ember.js
我正在尝试构建一个小的资产跟踪系统。 我有很多资产,而且有很多标签。 资产有很多标签,总之
我希望能够从列表中选择标签,并仅显示属于所选标签的资产。
我很难弄清楚如何获取选择视图以显示标签列表。 我觉得这与我的路线有关...
我正在尝试使用this.controllerFor('tags').set('content', this.store.find('tag')
将标签数据传递到资产路由,但似乎没有设置数据正确...
我也意识到我缺乏过滤列表的逻辑。
http://jsfiddle.net/viciousfish/g7xm7/
JavaScript代码:
App = Ember.Application.create({
ready: function() {
console.log('App ready');
}
});
App.ApplicationAdapter = DS.FixtureAdapter.extend();
//ROUTER
App.Router.map(function () {
this.resource('assets', { path: '/' });
this.resource('tags', { path: '/tags' });
});
//ROUTES
App.AssetsRoute = Ember.Route.extend({
model: function () {
return this.store.find('asset');
},
setupController: function(controller, model) {
this._super(controller, model);
this.controllerFor('tags').set('content', this.store.find('tag') );
}
});
//Tags Controller to load all tags for listing in select view
App.TagsController = Ember.ArrayController.extend();
App.AssetsController = Ember.ArrayController.extend({
needs: ['tags'],
selectedTag: null
});
//MODEL
App.Asset = DS.Model.extend({
name: DS.attr('string'),
tags: DS.hasMany('tag')
});
App.Tag = DS.Model.extend({
name: DS.attr('string'),
assets: DS.hasMany('asset')
});
//FIXTURE DATA
App.Asset.FIXTURES = [
{
id: 1,
name: "fixture1",
tags: [1,2]
},
{
id: 2,
name: "fixture2",
tags: [1]
},
{
id: 3,
name: "fixture3",
tags: [2]
}];
App.Tag.FIXTURES = [
{
id: 1,
name: 'Tag1',
assets: [1,2]
},
{
id: 2,
name: 'Tag2',
assets: [1,3]
}];
Moustachioed HTML:
<body>
<script type="text/x-handlebars" data-template-name="assets">
{{view Ember.Select
contentBinding="controller.tags.content"
optionValuePath="content.id"
optionLabelPath="content.name"
valueBinding="selectedTag"
}}
<table>
<tr>
<td>"ID"</td>
<td>"Name"</td>
</tr>
{{#each}}
<tr>
<td>{{id}}</td>
<td>{{name}}</td>
</tr>
{{/each}}
</table>
</script>
</body>
在你Ember.Select你有contentBinding="controller.tags.content"
你需要使用controllers
,而不是controller
。 因为需要,所以将引用的控制器添加到controllers属性中。 在您的情况下,您needs: ['tags']
AssetsController
中的needs: ['tags']
,因此在资产模板中,您只需要使用controllers.tags
来访问该实例。
这是更新的选择:
{{view Ember.Select
contentBinding="controllers.tags.content"
optionValuePath="content.id"
optionLabelPath="content.name"
valueBinding="selectedTag"
prompt="Select a tag"
}}
为了能够过滤数据,您可以创建一个取决于selectedTag
的计算属性。 然后使用selectedTag
值过滤内容。 如下所示:
App.AssetsController = Ember.ArrayController.extend({
needs: ['tags'],
selectedTag: null,
assetsByTag: function() {
var selectedTag = this.get('selectedTag');
var found = [];
this.get('model').forEach(function(asset) {
return asset.get('tags').forEach(function(tag) {
if (tag.get('id') === selectedTag) {
found.pushObject(asset);
}
});
});
return found;
}.property('selectedTag')
});
在模板中,您可以在每个助手中引用该属性:
{{#each assetsByTag}}
<tr>
<td>{{id}}</td>
<td>{{name}}</td>
</tr>
{{/each}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.