如何确定是否已将可选函数传递给Angular指令?

mcg*_*hix 4 javascript angularjs angularjs-directive

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

  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>
Run Code Online (Sandbox Code Playgroud)

这将显示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>
Run Code Online (Sandbox Code Playgroud)

这将显示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>
Run Code Online (Sandbox Code Playgroud)

这只会显示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;
    }

   ...
}

...
Run Code Online (Sandbox Code Playgroud)

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

Max*_*tin 6

你有链接attrs.只需检查是否label-function已定义且其值是否参考function

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

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

  • 右键bu用户可以输入值名称而不是函数 (2认同)