我正在尝试使用一个函数来返回值以呈现为 Angular JS ui.bootstrap 的工具提示。我需要这样做,以便我可以在 ng-repeat 循环中获得正确的工具提示。如果我直接访问 html 工具提示中的值(例如 tooltip="{{tooltips.rules.start}}
),则工具提示工作正常,但如果我使用函数 tooltipHelper
返回像 tooltip="tooltipHelper('rules', '{{fieldName}}')"
这样的值,则工具提示无法正常工作,例如,它只是将工具提示设置为字符串tooltipHelper('rules', 'start')
。
相关代码:
.JS
$scope.tooltips = {
rules: {
name: '',
weight: 'Sorts the rules, larger values sink to the bottom',
active: 'Enable/disable rule',
tag: 'Select a tag from the allowed tags list. To add tags to the allowed list go to the "tags" page',
start: 'Click to set the start time',
end: 'Click to set the end time',
activate: 'Click to set the activate datetime',
expire: 'Click to set the expire datetime'
}
};
$scope.tooltipHelper = function(type, name){
return $scope.tooltips[type][name];
};
HTML/Jade
div.required(ng-repeat="fieldName in datetime.fields", id="{{fieldName}}")
input.form-control.datetime(type="text", value="{{fieldName}}, tooltip="tooltipHelper('rules', '{{fieldName}}')")
问题是您需要将插值应用于 tooltipHelper 函数调用,这将导致双插标记。
通过以下方式之一解决问题:
- 内联函数工具提示帮助程序的代码:
div.required(ng-repeat="fieldName in datetime.fields", id="{{fieldName}}") input.form-control.datetime(type="text", value="{{fieldName}}, tooltip="{{tooltips[type][name]}}")
- 删除 {{字段名称}
- } 的内部插值,并将工具提示帮助程序函数更改为从作用域访问字段名称:
$scope.tooltipHelper = function(type){ var name = $scope.fieldName; 返回$scope.工具提示[类型][名称]; }; div.required(ng-repeat="fieldName in datetime.fields", id="{{fieldName}}") input.form-control.datetime(type="text", value="{{fieldName}}, tooltip="{{tooltipHelper('rules')}}")
事实证明,@umarius的答案和早晨的大脑让我找到了答案:
tooltip="{{tooltipHelper('rules', fieldName)}}"
我允许变量在没有插值的情况下传递,它工作正常,然后在我获得返回值后进行插值。