我创建了一个显示"下拉列表"的指令。以下是我使用的代码
HTML
<km-sselect km-left-title="Left" km-right-title="Right" km-model="sdsd" km-option="['AA','BB']"></km-sselect>
指令
app.directive('kmSselect', function($parse) {
return {
restrict: 'E',
replace: true,
templateUrl: 'select.html',
scope:true,
link: function(scope, element, attr) {
scope.leftTitle='';
if(angular.isUndefined(attr.kmLeftTitle)) {
scope.leftTitle='';
}
else {
scope.leftTitle=attr.kmLeftTitle+" ";
}
scope.rightTitle='';
if(angular.isUndefined(attr.kmRightTitle)) {
scope.rightTitle='';
}
else {
scope.rightTitle=" "+attr.kmRightTitle ;
}
var str1="n in ";
var str2=attr.kmOption;
var str3=attr.kmModel;
scope.model=attr.kmModel;
scope.repeat=str1.concat(str2);
scope.result=str1.concat(str3);
}
}
})
Select.html
<div>
<div ng-switch on="format">
<div ng-switch-when="kmForm">
<div>
<div class="floatLeft">
{{leftTitle}}
Repeat={{repeat}}
</div>
<select multiple ng-model="fdg" ng-click="testfunc(attrs.kmModel)">
<option ng-repeat={{repeat}} value="{{n}}">{{n}}</option>
</select>
</div>{{rightTitle}}</div>
</div>
<div ng-switch-when="kmPreview">
<div>
<div class="floatLeft">
title
result
</div>
<div class="floatLeft box">
<ul>
<li ng-repeat="result" class="hrline">{{n}}</li>
</ul>
</div>
</div>
</div>
</div>
我没有得到"Dropdown"中填充的值。
有人能告诉我哪里出了问题吗?
试图解决问题的方法看起来很复杂,可能很难实现。
为什么不创建一个隔离作用域?(该指令看起来是可重复使用的,因此应该使用隔离范围来防止意外后果)。
在这种情况下,您可以双向绑定选项和模型,只需将它们传递给指令中模板内的ng模型和ng select。
如果使用select,则需要为循环功能使用指令ng选项,而不是ng repeat。查看此处的文档
<select multiple ng-model="fdg" ng-click="testfunc(attrs.kmModel)" ng-options={{repeat}}></select>
然而,这有一种有趣的味道,我认为它不会起作用,因为在{{repeat}}有机会渲染之前,ng选项将被激发。
我建议将这个选择拉到它自己的指令中,这样它就可以一次完成所有操作——这可能会解决潜在的代码气味。
在release
可以转换为n in ['AA','BB']
之前,ng-repeat
已经确定它有一个无效的表达式。
解决方案是在链接函数中为集合创建一个作用域值,然后模板可以在标准ng-repeat
表达式中引用它。为此,请使用$eval
将属性从字符串转换为对象。
scope.kmOption = scope.$eval(attr.kmOption);
现在您只需在select.html中编写一个典型的表达式:
<option ng-repeat="n in kmOption" value="{{n}}">{{n}}</option>
而且,正如其他人所说,你通常会更好地使用ng-options
和select
,但同样的修复是必要的:
<select multiple ng-model="$parent.kmModel" ng-options="n for n in kmOption"></select>
更新
如果你像这样重写指令,你可以避免使用link
函数来$eval
选项:
app.directive('kmSselect', function($parse) {
return {
restrict: 'E',
replace: true,
templateUrl: 'select.html',
scope: {
kmModel: '=',
format: '=',
kmLeftTitle: '@',
kmRightTitle: '@',
kmOption: '@'
}
}
})
并更改模板,以便对kmOption
进行插值:
<select ng-model="$parent.kmModel" ng-options="n for n in {{kmOption}}"></select>
如果你想自己尝试代码,这里有一个关于Plunkr的工作演示。
旁注
事实上,考虑到ng-repeat
不允许类似的用法(如上所述):ng-repeat="n in {{kmOption}}"
,我很惊讶它能起作用。