2014-05-22 22 views
-1

中的選項之間要求一個屬性我正在創建一個角度指令,我希望用戶指定指令的「類型」。在指令

例如:

<my-directive type-a></my-directive> 

<my-directive type-b></my-directive> 

<my-directive type-c></my-directive> 



我知道我可以做:

<my-directive type="a"></my-directive> 


然後需要type屬性,但然後我在做字符串匹配。無論如何,通過要求「type-a」,「type-b」或「type-c」中的任何一個出現,可以這樣做嗎?

+0

字符串比較而不是什麼?屬性比較你需要確保類型是在編譯指令時設置的,否則你會拋出一個錯誤。這有什麼難的? – Mike

回答

1

沒有太多的背景信息,我想出了這個解決方案。

JSFIDDLE

所以基本上myDirective具有由類型指令共享一個控制器(type-atype-b ..等)。 type指令在myDirective範圍內設置類型。

myApp.directive('myDirective', function() { 

    return { 
     restrict: 'E', 
     controller: function($scope) { 
      $scope.type = ''; 

      this.setType = function(type){ 
       if($scope.type === '') $scope.type = type; 
       else throw 'type can be only defined once. Current type is '+$scope.type 
      } 
     }, 
     link: function(scope, elem, attrs) { 
      console.log(scope.type); 
     } 
    } 
}); 


myApp.directive('typeA', function() { 
    return { 
     restrict: 'A', 
     require: '^myDirective', 
     link: function(scope, elem, attrs, ctrl) { 
      ctrl.setType('typeA'); 
     } 
    } 
}); 

myApp.directive('typeB', function() { 
    return { 
     restrict: 'A', 
     require: '^myDirective', 
     link: function(scope, elem, attrs, ctrl) { 
      ctrl.setType('typeB'); 
     } 
    } 
}); 
0

我認爲你可以做<div data-my-directive="a"></div>這對於跨瀏覽器和w3c來說是一個更安全的選擇。然後該指令會是這樣的:

.directive('myDirective', function() { 
    return { 
    restrict: 'A', 
    scope: { 
     type: '=' 
    }, 
    link: function(scope,element,attrs){ 
    } 
    }; 
});