[英]Why are the blank options not being set for ng-options within a directive
我正在尝试创建AngularJS指令来管理<select>
输入的提示。 三种不同的模式如下:
allow-blank="true"
来实现 allow-blank
设置为除"true"
以外的任何值来"true"
但是, 空白选项永远不可用。
<select ng-options="tag.id as tag.name for tag in myTags">
<option ng-if="allowBlank === 'true'" value=""></option>
<option ng-if="allowBlank && allowBlank !== 'true'" value="">{{allowBlank}}</option>
</select>
myApp.directive('mySelector', ['$http', function($http) {
return {
templateUrl:'my-selector-template.html',
restrict: 'E',
scope: {
allowBlank: '@?'
},
replace: true,
controller: function ($scope) {
$scope.myTags = [
{"name":"aliquam in","id":1},
{"name":"massa velit","id":2},
{"name":"nec vestibulum","id":3}
];
}
};
}]);
问题是select
的内容被
包含在内
(请参阅下文)。 如果检查输出的元素,甚至看不到您在其中定义的选项标签。
由于您只是使用字符串,因此应该使用预链接功能,在其中您可以通过javascript添加正确的选项。 以下代码可以解决问题(Forked Plunk )。
link: {
pre: function(scope, element, attrs){
if(attrs.allowBlank === 'true') element.append('<option value=""></option>');
else if(attrs.allowBlank && attrs.allowBlank !== '') element.append('<option value="">' + attrs.allowBlank + '</option>');
}
}
编辑 select不会“包含”它的内容,因为@ lightswitch05指出select指令将以value=""
作为空节点( 源ref )获取第一个子对象。 然后稍后清除select的内容,并动态添加相关的<option>
标记( 源ref )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.