Filters are always useful for custom post-processing of our values. However with custom definition there is much more, that could be achieved.
Instance of our application provides function called filter
, that expects name and definition function of directive. The definition function accepts parameters context
, value
and param
.
context
is reference to context of space, where is filter presented.value
is the value, that will be post-processed.param
is custom parameter of filter to be useful in post-processing.
Our index.html
with our two filters. As you can see, the first one uses parameter. The second uses static value and no parameter, however it comulates filters.
<html ajsf="app">
<head>
<script type="text/javascript" src="js/nunjs.min.js"></script>
<script type="text/javascript" src="js/ajsf.min.js"></script>
<script type="text/javascript" src="js/app.js"></script>
</head>
<body>
<div ajsf-bind="user.balance | suffix ' EUR'"></div>
<div ajsf-bind="'home.salutation' | translate | suffix ' ' | suffix user.name"></div>
</body>
</html>
As usual, we have to prepare our application in app.js
with user object and messages, that will work as our translation data.
var app = ajsf('app', function(context) {
context.user = {
'name': 'Hero of our heart',
'balance': 123.45
}
context.messages = {
'home.salutation': 'Hello'
}
return context;
});
As first we should prepare suffix
filter. On the first try you can see, that there is no need to make lookup in context, if param starts with '
, it behaves as constant, otherwise it tries to lookup itself.
app.filter('suffix', function(context, value, param) {
return value + param;
});
As second we'll create our translate
filter, that will provides us simple translations.
app.filter('translate', function(context, value) {
return context.messages[value];
});
Previous chapter: 05. Custom Element Directives