【发布时间】:2016-02-05 06:42:32
【问题描述】:
我为引导警报创建了一个自定义指令。我的警报显示正常(硬代码和数据绑定)。根据警报类型,我想根据返回的范围值(成功、信息、警告、危险)在警报消息中显示一个唯一的标题。目前我将类型传递给<h1>,但我不想要这些值,它们需要自定义。
<!-- data binding example -->
<trux-alert ng-repeat="alert in alerts" type="{{alert.type}}" close="closeAlert($index)">{{alert.msg}}</trux-alert>
<!-- hard coded example -->
<trux-alert close="close" type="warning">This is an important warning message!</trux-alert>
在我的指令中,使用范围隔离范围:'@'(单向)
.directive('truxAlert', function() {
return {
scope: {
type: '@',
close: '&'
},
replace: true,
transclude: true,
template:
'<div class="alert" '+
'ng-class="[\'alert-\' + (type || \'warning\'), closeable ? \'alert-dismissible\' : null]" '+
'role="alert">'+
'<button ng-show="closeable" '+
'type="button" class="close" '+
'ng-click="close({$event: $event})" '+
'data-dismiss="alert" aria-label="Close">'+
'<span aria-hidden="true">×</span>'+
'<span class="sr-only">Close</span>'+
'</button>'+
'<h1>{{type}}</h1>'+
'<div ng-transclude></div>'+
'</div>',
link: function (scope, element, attrs) {}
}
});
如果我的所有值都是通过数据绑定提取的,这会更容易,但我需要允许手动硬编码选项。我知道单向隔离范围'@'我无法通过 DOM 操作更改这些值。我不能将 '=' 或 '&' 用于双向,因为值是字符串。
我该如何解决这个问题?
【问题讨论】:
-
你的意思是说,你想在
type="Something"这样的硬编码字符串中传递type值? -
是的,类型可以硬编码 type="string"。但只有 4 个可接受的值。
-
所以你可以直接从
attributes读出值,你不需要费心在隔离范围内传递它..如果它不会动态出现 -
或通过数据绑定,首选方法,仅取决于应用程序。也许我只需要只允许数据绑定选项。然后我可以从单个数据源数组中执行 {{alert.type}} 和 {{alert.heading}}
-
挑战是我试图在单个自定义指令中同时做到这两点