Troy Troy - 8 months ago 20
AngularJS Question

Is there a way to share config data among angular components?

I have about 10 components, and they all have the same bindings, and mostly the same controllers. The only thing that is different among each component is the templateUrl, and maybe a small addition to the controller.

Since Angular components take a config object rather than a factory function, does that mean I just have to use a bunch of copy/paste among my 10 components?

I know I could share config if I change them to directives, but I was hoping to keep these as (future-friendly) components.


You can use common config object and extend it with custom properties if it needs to:

var getConfig = function() {
  return {
    controller: function() { console.log('default controller'); },
    templateUrl: 'default.html',
    bindings: { }

// default component
app.component('one', getConfig())

// different templateUrl
app.component('two', angular.extend(getConfig(), {
  templateUrl: 'another.html'

// different controller
app.component('three', angular.extend(getConfig(), {
  controller: function() { console.log('another controller'); }

// ... and even extend controller itself
app.component('four', angular.extend(getConfig(), {
  controller: function() {
    // inherit default controller

    // and add custom functionality
    this.newMethod = function() {}