我正在尝试创建一个下拉指令,我想通过使用指令属性来指定 selects ng-options“选项值”和“选项描述”属性。查看代码以更好地理解...
这是我的指令。这显然行不通,但我认为它会描述我正在尝试做的事情......
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>
fiddle :http://jsfiddle.net/wXV6Z/1/
如果您对这个问题有解决方案,或者更有可能的是,对如何解决它有不同的看法,请告诉我!
谢谢 /安德烈亚斯
最佳答案
事实上,这是可行的。您需要做的唯一更改是删除 a[{{optValue}}]
和 a[{{optDescription}}]
周围的大括号,就像您不需要的那样不需要在那里插值。
optValue
和 optDescription
已经是范围内的字符串,因此 a[optValue]
和 a[optDescription]
将使您的代码正常工作,因为它们是在指令范围内计算的表达式。
关于AngularJS:带有自定义 ng-options 的下拉指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14967416/