mn93 mn93 - 3 months ago 15
AngularJS Question

using number filter in custom filter Angular JS

I am creating a custom filter for numbers in Angular 1.5 and I need to use the existing number filter in it.
I have this number format 3445 and I need to convert it to 3'445. For this purpose, first, I need to pass the input number to the number filter,

3445.05252 -> 3,445.1 -> 3'445.1

The problem is that I don't know how to use the number filter in my filter function. Here is my code:

app.filter('tick', function () {
return function(input, $number) {
var number =$number(input,1);
return number.toString().replace(",","'");
};


});

I can not use it like 3445.05252 | number:1 | tick. It must be with the number filter inside my filter.

here it is with $filter injected:

app.filter('tick', function () {
return function(input, $filter) {
var number = $filter('number')(input,1);
return number.toString().replace(",","'");
};


});

Here is the html code:

<div ng-app="myApp">
<div ng-controller="MainController">
<p> {{ 245258.222| tick }} </p>
</div>
</div>


And here is my js code:

var app = angular.module("myApp", []);

app.controller('MainController', ['$scope', '$window', function($scope, $window) {
$scope.price=2355;
$scope.url="http://google.com";
}]);
app.filter('tick', function () {
return function(input, $filter) {
var numberFilter= $filter('number');
var number =numberFilter(input,1);
return number.toString().replace(",","'");
};
});

Answer

The poster has updated the question so I'm adding another answer.

You can inject $filter into your own filter. This will allow you to retrieve the number filter by name and use it however you like.

Example:

app.filter('tick', function ($filter) {
    return function(input) {
        var numberFilter = $filter('number');
        var filteredInput = numberFilter(input, 1);
        return filteredInput.toString().replace(",", "'");
    };
});

Then in the HTML you can just say... 3445.05252 | tick