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

Roe*_*oel 0 handlebars.js ember.js

目前我正在尝试使用一个函数来观察 ember 模板(把手)中的控制器/组件的字段。

索引.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>
Run Code Online (Sandbox Code Playgroud)

索引.js

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

但这当然会返回构建错误:

{#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'
Run Code Online (Sandbox Code Playgroud)

知道如何实现这一目标吗?

Gau*_*rav 5

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

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

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

{{#if (contains array1 field1)}}

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