-1

Using Aurelia, i'm trying to use a converter inside a view model. But I don't know how to do it or if it's even possible.

With AngularJS, for example :
inside a view

<span>{{ 'hello' | uppercase }}</span>

inside a controller

$filter('uppercase')('hello');

With Aurelia
inside a view

<span>${ 'hello' | uppercase }</span>

inside a viewmodel

?????????
Flament Mickaël
  • 354
  • 2
  • 10
  • 2
    you could inject the converter in your viewmodel and call its toView() method? That being said, apart from a very simple use-case, I would rather write a getter property in the viewmodel and ditch the converter altogether, or write the converter logic in a service and call the service from your converter and viewModel, depending on the complexity and the number of times used within your app – Arne Deruwe Dec 21 '21 at 07:17
  • this is the answer I expected, thanks – Flament Mickaël Dec 21 '21 at 09:38

2 Answers2

2

Ok so, this is simple.
As our converters are classes, we just have to call the method toView from an instance.

import { UppercaseValueConverter } from './converters';

const convertedValue = new UppercaseValueConverter().toView('Hello');

In my case I was a little bit lost, because I use a library and can't import the converter class directly.

Flament Mickaël
  • 354
  • 2
  • 10
-1

In your viewmodel add the following code:

export class UppercaseValueConverter {
  toView(value) {
    return value?.toUpperCase();
  }
}

and then in your view:

<h1>${message | uppercase}</h1>

See a working example.

You can also add the value converter to the global resources section of your app to share it among all views.

Cristián Ormazábal
  • 1,457
  • 1
  • 9
  • 18
  • I didn't talk about converter viewmodel ; but others viewmodel. I expect an equivalent of what i wrote in angularjs. – Flament Mickaël Dec 20 '21 at 08:35
  • In this answer https://stackoverflow.com/questions/41122849/how-to-evaluate-an-aurelia-interpolation-expression-outside-a-view there is a converter used directly in a binding expression in a view-model. – Cristián Ormazábal Dec 20 '21 at 11:32