This seems like it should be easy, but I can't find documentation on it. I'm wondering how to make an Angular component (let's say a filter) reusable in different apps. I've made a simple filter that formats a phone number, and I'd like to be able to use it in any app. Currently it is declared like this:
var myModule = angular.module('myModule', ['ngSanitize']);
myModule.filter('formatFilter', function() {
return function(input) {
return input.replace(/(\d{3})(\d{3})(\d{4})/, "($1) $2-$3");
}
});
The question is how to make this filter reusable. Right now it's just attached to 'myModule', but how can I take it out of this file so I can reuse it elsewhere too?
You started OK by encapsulating your filter in a separate module. For other apps to use it, those apps will just need to include source code of your filter and declare dependency on a module:
angular.module('myApp',['myModule'])
You would probably like to rename your filter-holding module to something more meaningful, something like phoneFormatter
or sth.
Just as an example :
This is a reusable filter declared as a module, so only needs to be injected on the app:
Filter:
angular.module("lov-filter", []).filter('StartOnPage', function () {
return function (input, start) {
start = +start;
return input.slice(start);
}
});
App:
var demoApp = angular.module('demoApp', ['lov-filter']) .config(function () {
});
Used on this angular directive: https://github.com/rolandocc/lov-angular-directive
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With