5

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?

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Alright, so let's say I have a .js file called myModule.js. I just add that to my page, initialize my new module like you mentioned, call {{phoneNumber|formatFilter}} and that's it? p.s. the actual filter formats more that just phone numbers, hence the more abstract name. I just simplified it when asking the question.
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.