gpt4 book ai didi

javascript - 如何确定可选函数是否已传递到 Angular 指令中?

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:24:57 25 4
gpt4 key购买 nike

我有一个显示一些数据的指令,但我希望指令的用户能够控制数据的显示方式。我想让用户能够使用三个选项之一来控制显示。

  1. 传入一个用于显示的字符串
  2. 传入一个将被调用以生成字符串的函数
  3. 或者只展示原始数据

我无法发布整个指令(NDA 和所有指令)的代码,但它是一个使用 D3 显示环形图的指令。中间的数字是有问题的数据。所以假设环形图显示百分比,我可能希望中心的文字显示 55%。因此,假设 myValue 是作用域上的一个属性并设置为 55,这就是我想要做的:

<div ring-chart total="100"
remaining="{{myValue}}"
center-number-class="center-number-sm"
remaining-color="#0F79C0"
used-color="#C1D3E6"
chart-width="45"
chart-height="45"
ring-thickness="3"
label-text="{{myValue}}%"></div>

这将显示 55%或者做:

<div ring-chart total="100"
remaining="{{myValue}}"
center-number-class="center-number-sm"
remaining-color="#0F79C0"
used-color="#C1D3E6"
chart-width="45"
chart-height="45"
ring-thickness="3"
label-function="ringLabelFunction(remaining)"></div>

这将显示 ringLabelFunction(value) 返回的任何内容最后可以选择做:

<div ring-chart total="100"
remaining="{{myValue}}"
center-number-class="center-number-sm"
remaining-color="#0F79C0"
used-color="#C1D3E6"
chart-width="45"
chart-height="45"
ring-thickness="3"></div>

这只会显示 55。

在我的指令中

    ...
scope: {
total:"@",
remaining:"@",
valueSuffix: "@",
centerNumberClass: "@",
suffixClass: "@",
remainingColor: "@",
totalColor: "@",
chartWidth: "@",
chartHeight: "@",
ringThickness: "@",
labelFunction: "&",
labelText:"@"
},
link:function($scope, element, attrs) {
var labelContent;
if ($scope.labelText) {
labelContent = $scope.labelText;
} else if ($scope.labelFunction) { //<-- this is always true
labelContent = $scope.labelFunction({remaining:$scope.remaining});
} else { //so I never get to this
labelContent = $scope.remaining;
}

...
}

...

所以,简而言之,我正在寻找一种方法来确定是否实际设置了 $scope.labelFunction。

最佳答案

您有链接 attrs。只需检查是否定义了 label-function 并且它的值引用了 function

link:function($scope, element, attrs) {

if(attrs.labelFunction != undefined && typeof(attrs.onStuff) == 'function'){
scope.$eval(attrs.labelFunction);
}
}

关于javascript - 如何确定可选函数是否已传递到 Angular 指令中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20360839/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com