我有一个模型,路线和控制器的简单应用程序。我无法从控制器中的模型访问数据。我使用ember-cli所以我有以下结构:
/app/router.js
var Router = Ember.Router.extend({
location: config.locationType
});
Router.map(function() {
this.route('logs',{path: '/'});
});
export default Router;
/app/routes/logs.js
export default Ember.Route.extend({
controllerName: 'logs',
model: function() {
return this.store.find('logs');
}
});
/app/models/logs.js
export default DS.Model.extend({
ip: DS.attr('string'),
timestamp: DS.attr('number'),
visited_resource: DS.attr('string'),
pretty_string: DS.attr('string')
});
/app/controllers/logs.js
export default Ember.Controller.extend({
url: function() {
var model = this.get('model');
var basePath = "http://example.com";
var path = model.visited_resource;
return basePath+path
}.property('visited_resource')
});
我的问题是model.visited_resources
或this.get('model.visited_resources')
或this.get('model.[any param]')
未定义。
如果我记录整个模型对象并检查它,我的所有数据都在那里! ! http://i.stack.imgur.com/nkvyT.png
只是控制器无法访问它。我究竟做错了什么?
答案 0 :(得分:2)
您的模型是查看该屏幕截图( content: Array[5]
)的数组,因此如果您想要单个项目,则需要获取第一个对象:
export default Ember.Controller.extend({
url: Ember.computed('model', function() {
var logs = this.get('model');
var firstLog = logs.get('firstObject');
var path = firstLog.get('visited_resource');
var basePath = 'http://example.com';
return basePath + path;
});
});
或迭代每个项目并返回一个数组:
export default Ember.Controller.extend({
urls: Ember.computed('model', function() {
var logs = this.get('model');
var basePath = 'http://example.com';
var urls = logs.map(function(model) {
var path = model.get('visited_resource');
return basePath + path;
});
return urls;
})
});
要在模型上创建计算属性,请在模型上执行:
export default DS.Model.extend({
ip: DS.attr('string'),
timestamp: DS.attr('number'),
visited_resource: DS.attr('string'),
pretty_string: DS.attr('string'),
url: Ember.computed('visited_resource', function() {
var basePath = 'http://example.com';
var path = this.get('visited_resource');
return basePath + path;
})
});
并且您将像任何其他财产一样访问url
媒体资源:
export default Ember.Controller.extend({
url: Ember.computed('model', function() {
var logs = this.get('model');
var firstLog = logs.get('firstObject');
return firstLog.get('url');
})
})
您还可以使用setupController
显式设置模型:
export default Ember.Route.extend({
controllerName: 'logs',
model: function() {
return this.store.find('logs');
},
setupController: function(controller, model) {
controller.set('model', model);
// or first item only
controller.set('model', model.get('firstObject'));
}
});