handleman
8/5/2015 - 3:48 PM

This is a custom filter to show a bytes filesize in better way.

This is a custom filter to show a bytes filesize in better way.

// add the filter to your application module
angular.module('myApp', ['filters']);

/**
 * Filesize Filter
 * @Param length, default is 0
 * @return string
 */
angular.module('filters', [])
  .filter('Filesize', function () {
		return function (size) {
			if (isNaN(size))
				size = 0;

			if (size < 1024)
				return size + ' Bytes';

			size /= 1024;

			if (size < 1024)
				return size.toFixed(2) + ' Kb';

			size /= 1024;

			if (size < 1024)
				return size.toFixed(2) + ' Mb';

			size /= 1024;

			if (size < 1024)
				return size.toFixed(2) + ' Gb';

			size /= 1024;

			return size.toFixed(2) + ' Tb';
		};
	});

/**
 * Usage
 * var myFile = 5678;
 *
 * {{myText|filesize}}
 *
 * Output
 * "5.54 Kb"
 *
 */