Shift 'n Tab
Shift 'n Tab

Reputation: 9443

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

Currently Im trying to use a function that observes a field of a controller/component in ember template (handlebars).

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'),

But this of course returns a build error:

{#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'

Any idea how to achieve this?

Upvotes: 0

Views: 2227

Answers (2)

Lux
Lux

Reputation: 18240

Just replace your observer function with a computed property:

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

Upvotes: 0

Gaurav
Gaurav

Reputation: 12796

  1. You can't call a function from a template, except using an action. You can only reference properties, such as fields and computed properties.

  2. Observers are generally not a good idea

  3. Are you really trying to determine if the value of field1 is in an array? Let's assume the array is found at array1. Then you could write a helper named contains:

{{#if (contains array1 field1)}}

But someone has already written this. Welcome to the wonderful Ember community of addons! See https://github.com/DockYard/ember-composable-helpers#contains

Upvotes: 5

Related Questions