如何从Ember中的模板调用控制器功能? [英] How do I call a controller function from a template in Ember?

查看:45
本文介绍了如何从Ember中的模板调用控制器功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我有一个模板,该模板可对一组项目进行迭代,并且我想针对每个项目调用一个特定于控制器的函数,而不是模型级别的问题:

Let's say I have a template which iterates over a collection of items, and I want to call a function with each item which is specific to the controller, and not a model-level concern:

{{#each people as |person|}}
  icon name: {{findIconFor(person)}}
{{/each}}

我想定义 findIconFor ,因为这是特定于此特定视图的。

I'd like to define findIconFor in the controller, because this is something specific to this particular view.

export default Ember.Controller.extend({
  findIconFor: function(person) {
    // figure out which icon to use
  }
);

但这不起作用。该模板无法编译。解析错误:期望'STRING','NUMBER','ID','DATA','INVALID'

But that doesn't work. The template fails to compile. Parse error: Expecting 'STRING', 'NUMBER', 'ID', 'DATA', got 'INVALID'

什么是

What is the "ember way" to do this?

推荐答案

我会在控制器中使用计算属性:

I'd use a computed property in the controller:

iconPeople: Ember.computed('people.@each', function(){
  var that = this;
  return this.get('people').map(function(person){
    return {
      'person': person,
      'icon': that.findIconFor(person)
    };
  });
})

现在您可以从 {{person.icon}} {{person.person.name}} 中的名称。您可能需要对此进行改进(并且代码未经测试),但这是一般性的想法。

Now you could get the icon from {{person.icon}} and the name from {{person.person.name}}. You might want to improve on that (and the code is untested), but that's the general idea.

这篇关于如何从Ember中的模板调用控制器功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆