Following code should give you a clean and simple example of custom filter using AngularJS.
HTML code:
———————
<!doctype html>
<html >
<head>
<script src=”src=”http://code.angularjs.org/angular-1.0.0rc6.min.js”></script >
<script src=”filter.js“></script>
</head>
<body>
<div ng-app=”testFilterApp“>
<label>Size in Byte:</label>
<input type=”text” ng-model=”sizeInB” placeholder=”Enter a name here”>
<hr>
<h2>Human Readable Size (precision:3) {{sizeInB | sizeConverter:3}}!</h2>
<h2>Human Readable Size (precision: not defined) {{sizeInB | sizeConverter}}!</h2>
</div>
</body>
</html>
AngularJS code (filter.js)
———————————-
<pre>
angular.module(‘testFilterApp‘, []);
// add the filter to your application module
angular.module(‘testFilterApp‘, [‘filters’]);
/**
* Size Converter Filter
* @Param sizeInByte
* @Param precision default is 1
*/
angular.module(‘filters’, []).
filter(‘sizeConverter’, function () {
return function (size, precision) {
if (precision == 0 || precision == null){
precision = 1;
}
if (size == 0 || size == null){
return “”;
}
else if(!isNaN(size)){
var sizes = [‘Bytes’, ‘KB’, ‘MB’, ‘GB’, ‘TB’];
var posttxt = 0;
if (size < 1024) {
return Number(size) + ” ” + sizes[posttxt];
}
while( size >= 1024 ) {
posttxt++;
size = size / 1024;
}
var power = Math.pow (10, precision);
var poweredVal = Math.ceil (size * power);
size = poweredVal / power;
return size + ” ” + sizes[posttxt];
}else{
console.log(‘Error: Not a number.’);
return “”;
}
};
});
</pre>
This works too :
angular.module(‘filters’, [])
.filter(‘humanSize’, function () {
return function (bytes, index) {
if(bytes <= 0) return 0;
var s = ['bytes', 'kB', 'MB', 'GB', 'TB', 'PB'];
var e = Math.floor(Math.log(bytes) / Math.log(1024));
return (bytes / Math.pow(1024, Math.floor(e))).toFixed(2) + " " + s[e];
}
});
# Removing while loop is a good advancement.
# toFixed() method doesn’t round. So toFixed(1.567)KB = 1.56 KB but it should be 1.57KB.