2016-06-30 4 views
1

私は約10のコンポーネントを持っています。それらはすべて同じバインディングを持ち、ほとんど同じコントローラを持っています。各コンポーネント間で異なる唯一のものはtemplateUrlであり、おそらくコントローラへの小さな追加です。角度成分間で設定データを共有する方法はありますか?

角型コンポーネントは、ファクトリ関数ではなくconfigオブジェクトをとるため、10個のコンポーネントのうちでコピー/ペーストを使用するだけですか?

私はそれらをディレクティブに変更すると、私はconfigを共有できると知っていますが、私はこれを(将来に向いている)コンポーネントとして保持したいと考えていました。

答えて

1

あなたは、共通のconfigオブジェクトを使用して、それが必要な場合はカスタムプロパティでそれを拡張することができた:私は元/ベースコントローラと依存性注入を使用することができるだろう、ということでした場合

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 
    getConfig().controller.call(this) 

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

? – Troy

+0

はい、もちろんです。 – dfsq

+0

詳細な例をありがとう。例4では、 'config.controller.call(this)'という行は私に無限の再帰を与えます。私はそれが基本設定(?)で別の名前が必要だと思うが、それは例1と2を壊すだろう... – Troy

関連する問題