2014-10-28 94 views
-1

我正在儘量保持我的角度項目儘可能模塊化。我目前有3個嵌套指令構成我的項目的基礎。在角度繼承指令

最低指令總是具有相同的核心功能和範圍對象,但根據用例需要額外的範圍對象和功能。該應用程序非常大,因此儘可能分離所有內容非常重要,並遵循DRY原則。

在Python風格的OOP中,我會繼承所有的屬性和函數,然後添加到它們。 Angular中有類似的東西嗎?

例如:

基礎

myApp.directive('itemOption', function() { 
    return { 
     restrict: 'E', 
     templateUrl: "item_option.html", 
     scope: { 
      'lowest': '=', 
      'middle': '=', 
      'high': '=', 
      'ngModel': '=', 
     }, 
     controller: function ($scope) { 
      $scope.prop1 = "Default 1" 
      $scope.prop2 = "Default 2" 
     } 
    } 
} 

將被代替基地

myApp.directive('itemOptionVariation1', function() { 
    return { 
     restrict: 'E', 
     templateUrl: "item_option.html", 
     scope: { 
      'lowest': '=', 
      'middle': '=', 
      'high': '=', 
      'ngModel': '=', 
     }, 
     controller: function ($scope) { 
      $scope.prop1 = "Default 1" 
      $scope.prop2 = "Default 2" 

      // Unique to this directive 
      $scope.prop900 = "Penguins" 
     } 
    } 
} 

而另一個

myApp.directive('itemOptionVariation2', function() { 
    return { 
     restrict: 'E', 
     templateUrl: "item_option.html", 
     scope: { 
      'lowest': '=', 
      'middle': '=', 
      'high': '=', 
      'ngModel': '=', 
     }, 
     controller: function ($scope) { 
      $scope.prop1 = "Default 1" 
      $scope.prop2 = "Default 2" 

      // Unique to this directive 
      $scope.prop3 = "This is awesome" 
     } 
    } 
} 

回答

2

您可以使用重複指令要求:[^ parent_directive1,^ parent_directive2]作爲指令屬性。請檢查下面的例子。

myApp.directive('itemOptionVariation2', function() { 
    return { 
     restrict: 'E', 
     templateUrl: "item_option.html", 
     require: ['^itemOption', '^itemOptionVariation1'], 

這不完全是繼承,而是一種構圖。但是,這已經解決了我的需求。

+0

我看到這是一個很好的解決方案。你能解釋一下你的意思,而不是遺傳嗎?我知道它解決了這個問題,我總是遇到麻煩總是看到原因。 – Kazanz 2014-10-29 13:18:35

+0

這是我的理解,而不是Java中的繼承,在Angular中,您必須定義繼承的屬性和控制器。請參閱這個對話和提供更多關於實現的詳細信息。 http://plnkr.co/edit/djNk8PPzXvngZOvAirMu?p=preview http://stackoverflow.com/questions/19111696/scope-in​​heritance-for-angular-directives – Aviro 2014-10-29 20:53:45

+1

謝謝@Aviro。這是我的解決方案,繼承了指令之外的控制器。 https://gist.github.com/Kazanz/379c1dd5507d15ec7977 – Kazanz 2014-10-30 14:59:52