2013-02-19 84 views
4

我想創建一個下拉指令,我想指定選擇ng選項「選項值」和「選項描述」屬性通過指定它們與指令屬性。請參閱代碼以獲得更好的理解...AngularJS:下拉指令與自定義ng選項

這是我的指令。這顯然不起作用,但我認爲它會描述我想要做什麼...

app.directive('dropdown', function(){ 
return { 
    restrict: 'E', 
    scope: { 
     array: '=' 
    }, 
    template: '<label>{{label}}</label>' + 
       '<select ng-model="ngModel" ng-options="a[{{optValue}}] as a[{{optDescription}}] for a in array">' + 
        '<option style="display: none" value="">-- {{title}} --</option>' + 
       '</select>', 
    link: function (scope, element, attrs) { 
     scope.label = attrs.label; 
     scope.title = attrs.title; 
     scope.optValue = attrs.optValue; 
     scope.optDescription = attrs.Description; 
    } 
}; 

});

...這裏是我要如何使用它

<dropdown title="Choose ferry" label="Ferries" array="ferries" opt-value="Id" opt-description="Description"></dropdown> 
<dropdown title="Choose route" label="Routes" array="routes" opt-value="Code" opt-description="Name"></dropdown> 

和提琴:http://jsfiddle.net/wXV6Z/1/

如果你有解決這個問題,或者更可能的是,有一個關於如何解決它的不同意見,請讓我知道!

感謝 /安德烈亞斯

回答

4

其實,這是可行的。您需要做的唯一更改是刪除圍繞a[{{optValue}}]a[{{optDescription}}]的大括號,因爲您不需要在那裏進行插值。

optValueoptDescription已經在範圍字符串,所以a[optValue]a[optDescription]將會使你的代碼工作得很好,因爲它們是在你的指令的範圍計算的表達式。

Here's an updated version of your fiddle

+0

良好的通話。由於每個部分都是通過Angular進行評估的,因此可以將這些值從$範圍中提取出來。 – 2013-02-20 02:06:46

+0

這正是我要找的。非常感謝你! – larchii 2013-02-20 07:21:28

+0

這幫助我解決了我在自己的自定義指令中遇到的一個問題,這個問題非常類似於此。謝謝! – Fooberichu 2014-09-11 21:51:39