Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a reusable AngularJs components

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?

like image 242
Spencer Avatar asked Feb 04 '13 21:02

Spencer


2 Answers

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.

like image 166
pkozlowski.opensource Avatar answered Sep 19 '22 12:09

pkozlowski.opensource


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

like image 36
RolandoCC Avatar answered Sep 20 '22 12:09

RolandoCC