问题
I have a directive that displays some data but I want to user of the directive to be able to control how that data is displayed. I would like to allow a user to be able control the display using one of three options.
- pass in a string to use for the display
- pass in a function that will be called to generate the string
- or just show the raw data
I can't post the code for the entire directive (NDA and all) but it is a directive for showing a ring chart using D3. The number in the middle is the piece of data in question. So assuming the ring chart is showing a percentage, I may want the text in the center to say 55%. So assuming myValue is a property on the scope and is set to 55, here is what I would like to do:
<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>
which would show 55% or do:
<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>
which would show whatever ringLabelFunction(value) returns and finally have the option to do:
<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>
which would just show 55.
In the directive I have
...
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;
}
...
}
...
So, in short I am looking for a way to determine if $scope.labelFunction has actually been set.
回答1:
You have link attrs
. Just check if label-function
is defined and its value refers to function
link:function($scope, element, attrs) {
if(attrs.labelFunction != undefined && typeof(attrs.onStuff) == 'function'){
scope.$eval(attrs.labelFunction);
}
}
回答2:
Check to see if it's a function:
} else if ($scope.labelFunction && typeof($scope.labelFunction) == "function") {
来源:https://stackoverflow.com/questions/20360839/how-to-determine-if-an-optional-function-has-been-passed-into-an-angular-directi