display text prefix only if data is present - angularjs

I have some AngularJS code that displays an outstanding balance only if their is a balance to display.
{{Customer.LastName}}, {{Customer.FirstName}} ${{Customer.OutstandingBalance}}
What I would like to do is not display the dollar sign ($) at all if there is no outstanding balance. How do I make the dollar sign dependent on the value of Customer.OutstandingBalance?

I think except obvious suggestions like "wrap it in <span ng-show="Customer.OutstandingBalance">
you could do smth like this: {{Customer.LastName}}, {{Customer.FirstName}} {{Customer.OutstandingBalance ? '$' : ''}}{{Customer.OutstandingBalance}}

Use custom filter with inbuilt currency filer.
app.filter('myCurrency', function($filter){
return function(input){
return input ? $filter('currency')(input) : '';
};
});
in view use
{{Customer.LastName}}, {{Customer.FirstName}} {{Customer.OutstandingBalance | myCurrency}}
Here's plunker demo
http://plnkr.co/edit/ocqmiz4tNX49R8rG8VA7?p=preview

You could have a span that only is showed based on the OutstandingBalance:
<span ng-show="Customer.OutstandingBalance != 0">$</span> {{Customer.OutstandingBalance}}

Related

AngularJs currency in Euro [duplicate]

How to move the symbol euro from the front of the value to after it?
Example:
{{product.price | currency : "€"}} will produce € 12.00
but I would like 12.00 €
You don't have to hack the currency filter!
AngularJS has a great support for i18n/l10n. The currency filter uses the default currency symbol from the locale service and positions it based on the locale settings.
So it's all about supporting and setting the right locale.
<script src="i18n/angular-locale_de-de.js"></script>
If you are using npm or bower all locales are available via the angular-i18n package.
<span>{{ product.price | currency }}</span>
will now produce the following output:
65,95 €
Supporting multiple localizations
If you want to support multiple localizations be careful with the currency symbol as it changes to the default currency of the used locale. But 65,95 € are different to $65,95. Provide the currency symbol as parameter to be safe:
<span>{{ product.price | currency:'€' }}</span>
In de-de the output would still be 65,95 € but if the location is eg. en-us it would be €65.95 (which is despite some other sayings the correct format to display euro prices in English).
To learn more about angular and i18n/l10n refer to the developer guide.
You can't with the currency filter. You could write your own, or just use the number filter.
{{(produce.price | number:2) + "€"}}
use this trick.
<div>{{product.price | currency : '' }} €</div>
The solutions proposed are all dirty.
at first, the filter allow change symbol by add it as parameter:
{{product.price | currency : "€"}}
but the right way is localize your app as suggested by #Andreas
if you localize your app for example with italian locale setting (it-it) inside your app you need only invoke the filter to obtain the € sign.
{{product.price | currency }}
Italian locale setting put the Euro sign before the currency value.
You could change che locale value, or much better override them as proposed in the follow linked answer:
Why AngularJS currency filter formats negative numbers with parenthesis?
you could override the locale setting put your currency symbol (\u00A4) as a prefix or suffix for positive value and negative too.
app.config(['$provide', function($provide) {
$provide.decorator('$locale', ['$delegate', function($delegate) {
if($delegate.id == 'it-it') {
$delegate.NUMBER_FORMATS.PATTERNS[1].negPre = '\u00A4\u00a0-';
$delegate.NUMBER_FORMATS.PATTERNS[1].negSuf = '';
$delegate.NUMBER_FORMATS.PATTERNS[1].posPre = '\u00A4\u00a0';
$delegate.NUMBER_FORMATS.PATTERNS[1].posSuf = '';
}
return $delegate;
}]);
}]);
so after this instruction the filter:
{{product.price | currency}}
will produce the follow output
€ 12
Angularjs has a great support for internationalization and localization.
The application of internationalization and localization depends on the scope of your application.
For example if your application only support euro then you need only the localization for euro and does not require all the currency and its formatting.
In such situation (Assuming your situation is similar to above ) you can create an app configuration and set locale as the localization you required using some decorators. A decorator function intercepts the creation of a service, allowing it to override or modify the behavior of the service.
angular
.module('app', [])
.config(['$provide', function($provide) {
$provide.decorator('$locale', ['$delegate', function($delegate) {
$delegate.NUMBER_FORMATS = {
DECIMAL_SEP: '.',
GROUP_SEP: ',',
PATTERNS: [{ // Decimal Pattern
minInt: 1,
minFrac: 0,
maxFrac: 3,
posPre: '',
posSuf: '',
negPre: '-',
negSuf: '',
gSize: 3,
lgSize: 3
}, { //Currency Pattern
minInt: 1,
minFrac: 0,
maxFrac: 1,
posPre: '\u00A4',
posSuf: '',
negPre: '(\u00A4',
negSuf: ')',
gSize: 3,
lgSize: 3
}],
CURRENCY_SYM: '€'
}
return $delegate;
}]);
}])
.controller('appController', ['$scope', function($scope) {
$scope.price = 20.55;
}])
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="appController">
Price : {{price | currency}}
</div>
</div>
The above configuration shows all possible values for decimal and currency settings.
You can change according to your requirements at app level.
If you dont want the effect to be in entire application better is to go for a directive
It's quite an old question, it's different these days.. Maybe it was back then aswell..
So if someone else finds this..
But you need to include the correct locale to get the correct currency formatting in the currency filter.
Check the angular documentation, for example dutch currency formatting is € 5,00 While english is 5,00 € and american is €5.00
I use this solution in my project (in production) in France (It must ALWAYS show 5.00€, NEVER show €5.00):
<span>Price: {{product.price| currency:""}} €</span>
DEMO
Please, read the real question of this post (Angular Js currency, symbol euro after) before downvote too quickly!!!!!
Using the locale (as explained in the answer in this thread -
at Angular Js currency, symbol euro after) seems like the most correct way to do it, but it doesn't seem to offer the flexibility to put the currency symbol or name where you want it relative to the value you're referencing to. If you need to have your currency symbol after your value, you could have a separate product.currency field and interpolate that after (or before) your price value.
So if you have product.price = 40 and product.currency = '€', you could display it as 40 € with {{product.price}} {{product.currency}}. Or € 40 by reversing the fields: {{product.currency}} {{product.price}}.
You'd probably want to format the product.price values via the decimal pipe if you did that (https://angular.io/api/common/DecimalPipe). - So "40.00 €" would be : {{product.amount | number:'2.2-2'}} {{product.currency}}.
fyi - in this case, I'd probably have a separate field product.currency and product.currencySymbol (e.g. "USD" and "$" respectively), but then you're getting more into the functionality of the locale as referenced in the other answer I link above. But if you need to place the currency name or symbol in a different location relative to the value than what Angular will let you do via its native pipes, and want to use a currency that's specific to a record or set that you're working with without hard-coding its symbol or name on the page (e.g. if you have multiple currencies you're displaying), this is one way to do it dynamically.
You can create a filter :
app.filter('euroFormat', function () {
return function (input) {
return input+' \u20AC';
};
});
and apply it on your html code with :
<span>Price: {{product.price| euroFormat}}</span>

AngularJS limitTo using HTML tags

I have some bindings in AngularJS and I want to limit the length of characters displayed. It's a quite simple question when you have just a simple text content.
However, I have text that contains HTML tags:
$scope.text = "<span><h1>Example</h1><p>Special Text</p></span>"
and also
$scope.maxNumberOfChar = 10;
When I use the following line it counts the number of chars taking into account HTML tags.
Which could be the best solution to solve this problem and count only the number of chars, discarding HTML tags?
Thanks in advance
I've created a solution, using a simple filter and regex operations.
var appFilters = angular.module('myApp.filters', [])
.filter('limitHtml', function() {
return function(text, limit) {
var changedString = String(text).replace(/<[^>]+>/gm, '');
var length = changedString.length;
return changedString.length > limit ? changedString.substr(0, limit - 1) : changedString;
}
})
and the correspondent usage, similar to limitTo filter
<span ng-bind-html="text | limitHtml: maxNumberOfChar"></span>
Note that, in this case I am also using an html-binding, specific of my solution.
I created a filter, the logic is not so good, but it works
<span ng-bind-html="text | limitHtml:maxNumberOfChar"></span>
jsfiddle.net/4x6z283a/1/
To count only the number of non HTML chars, use something similar to the answer to this question:
angularjs to output plain text instead of html
For example:
var text = "<span><h1>Example</h1><p>Special Text</p></span>";
var length = String(text).replace(/<[^>]+>/gm, '').length;
alert(length);
I've included a further example here: http://jsfiddle.net/n3qjm2u5/
Why not displaying it based on a filter length?
Just add a limitTo filter
{{ text| limitTo:maxNumberOfChar }}

Currency formatting Canadian French with custom filter

I am using a custom filter that utilizes angular's basic currency filter to display a monetary value based on a locale setting of en_CA or fr_CA. The display will either look like $123,456,789.99 or 123.456.789,99$ respectively. My question comes down to how do I make the angular currency filter handle formatting the value or must I do string replacements?
Filter code:
angular.module('plunker').filter('customCurrency',
[ '$filter', function(filter) {
var currencyFilter = filter('currency');
return function(languageCode,amount, currencySymbol) {
if(languageCode=='en_CA'){
currencySymbol='$';
}else if(languageCode=='fr_CA'){
currencySymbol='';
}
return currencyFilter(amount, currencySymbol);
}
} ]);
The plunker is located at http://plnkr.co/edit/7JJhd6.
Just went with the string replacement. The plunker from the original question contains the working example that I ended up using.

how to make full text combination filter in angularjs

I tried to make angularjs full text search like in this plunker
http://plnkr.co/edit/PwcteF6WAtuAOj3ZDKLe?p=preview
I've tried many combination but none works..
e.g I want to search cross column like 'alex big-mary' or 'alex 800' or 'mary big' but not works
alex 555 works because 555 exist right after alex word
I dont know any built-in filter that would perform an OR-like search. You can define your own filter that would fit your needs:
angular.module('App', []).filter('search', function($filter){
return function(items, text){
if (!text || text.length === 0)
return items;
// split search text on space
var searchTerms = text.split(' ');
// search for single terms.
// this reduces the item list step by step
searchTerms.forEach(function(term) {
if (term && term.length)
items = $filter('filter')(items, term);
});
return items
};
});
See this code in action using this Plunkr: simple OR search filter
You will need to create a custom filter that will take your data and tokenize it on per row basis and only display those rows that match the strings that you enter.
Here are the docs for creating custom filters:
http://docs.angularjs.org/guide/dev_guide.templates.filters.creating_filters

How to extend or override existing filters in angularjs?

Is it possible to extend existing "standard" filters (date, number, lowercase etc)?
In my case I need to parse date from YYYYMMDDhhmmss format so I'd like to extend (or override) date filter instead of writing my own.
I prefer to implement the decorator pattern, which is very easy in AngularJS.
If we take #pkozlowski.opensource example, we can change it to something like:
myApp.config(['$provide', function($provide) {
$provide.decorator('dateFilter', ['$delegate', function($delegate) {
var srcFilter = $delegate;
var extendsFilter = function() {
var res = srcFilter.apply(this, arguments);
return arguments[2] ? res + arguments[2] : res;
}
return extendsFilter;
}])
}])
And then in your views, you can use both.. the standard output and the extended behavior. with the same filter
<p>Standard output : {{ now | date:'yyyyMMddhhmmss' }}</p>
<p>External behavior : {{ now | date:'yyyyMMddhhmmss': ' My suffix' }}</p>
Here is a working fiddle illustrating both techniques:
http://jsfiddle.net/ar8m/9dg0hLho/
I'm not sure if I understand your question correctly, but if you would like to extend functionality of existing filters you could create a new filter that decorates an existing one. Example:
myApp.filter('customDate', function($filter) {
var standardDateFilterFn = $filter('date');
return function(dateToFormat) {
return 'prefix ' + standardDateFilterFn(dateToFormat, 'yyyyMMddhhmmss');
};
});
and then, in your template:
{{now | customDate}}
Having said the above, if you simply want to format a date according to a given format this can be done with the existing date filter:
{{now | date:'yyyyMMddhhmmss'}}
Here is the working jsFiddle illustrating both techniques: http://jsfiddle.net/pkozlowski_opensource/zVdJd/2/
Please note that if a format is not specified AngularJS will assume that this is 'medium' format (the exact format depends on a locale). Check http://docs.angularjs.org/api/ng.filter:date for more.
The last remark: I'm a bit confused about the 'parse from' part of your question. The thing is that filters are used to parse an object (date in this case) to string and not vice verse. If you are after parsing strings (from an input) representing dates you would have to look into NgModelController#$parsers (check the "Custom Validation" part in http://docs.angularjs.org/guide/forms).

Resources