如何在模板中的 IF 语句中使用带参数的函数

How to use function with arguments in IF statement in the template

目前我正在尝试使用一个函数来观察 ember 模板(车把)中 controller/component 的字段。

index.hbs

<div>
   {{ input value=model.field1 }}
   {{if hasFieldError('field1')}}
      <span>This field is required</span>
   {{/if}}
</div>

<div>
   {{ input value=model.field2 }}
   {{if hasFieldError('field2')}}
      <span>This field is required</span>
   {{/if}}
</div>

index.js

hasFieldError: function(val) {
   return true if val is found in an array
}.observes('field1', 'field2'),

但这当然是 returns 构建错误:

{#if hasFieldError('compa ----------------------^ Expecting 
'CLOSE_RAW_BLOCK', 'CLOSE', 'CLOSE_UNESCAPED', 'OPEN_SEXPR', 
'CLOSE_SEXPR', 'ID', 'OPEN_BLOCK_PARAMS', 'STRING', 'NUMBER', 
'BOOLEAN', 'UNDEFINED', 'NULL', 'DATA', 'SEP', got 'INVALID'

知道如何实现吗?

  1. 您不能从模板调用函数,除非使用操作。您只能引用属性,例如字段和计算属性。

  2. 观察者通常不是一个好主意

  3. 您真的要确定 field1 的值是否在数组中吗?假设数组位于 array1。然后你可以编写一个名为 contains:

  4. 的助手

{{#if (contains array1 field1)}}

但是已经有人写过了。欢迎来到精彩的 Ember 插件社区!参见 https://github.com/DockYard/ember-composable-helpers#contains

只需用计算 属性:

替换您的观察者函数
hasFieldError: Ember.computed('field1', 'field2', function(val) {
   return true if val is found in an array
}),