What's the best way to access dashboard variables within a plugin?

My dashboard has a couple of variables, what is the best way to expose the variable values within a plugin?

expose? you want the plugin to show them or use them? templateSrv.replace to interpolate strings

Ok. Now a similar question. How to I programmatically update a dashboard variable?

It’s tricky, there is no supported API for plugins to do that yet.

The following code updates all of the dashboard panels, but does not update the variable dropdown selectors on my dashboard. Any hints at how to get those updated correctly?

const { $location, $q, $scope, variableSrv } = this;

$location.search({
  ...$location.search(),
  ...variables
});

return $q.all(variableSrv.variables.map((variable) => {
  const urlValue = variables[`var-${variable.name}`];
  if (urlValue !== undefined) {
    return variable.setValueFromUrl(urlValue);
  }

  return false;
})).then(() => {
  variableSrv.templateSrv.updateTemplateData();
  $scope.$root.$broadcast('refresh');
});
1 Like

as I said there is no supported way to do this, you should not use setValueFromUrl,

Is there a supported function to refresh everything based on the current url query string?

we actually do this in the kubernete app, it has a panel that updates template variables:

2 Likes

Awesome, thanks. I will take a look at that approach.

UPDATE: this code is doing what I want:

const { $scope, variableSrv } = this;

Object.keys(replaceVariables).reduce((acc, variableKey) => {
  const variable = variableSrv.variables.find(v => v.name === variableKey);
  if (variable) {
    const newValue = replaceVariables[variableKey];
    variable.current.text = newValue;
    variable.current.value = newValue;
    return acc.then(() => variableSrv.updateOptions(variable))
              .then(() => variableSrv.variableUpdated(variable))
              .then(() => $scope.$emit('template-variable-value-updated'));
  }

  return acc;
}, Promise.resolve()).then(() => {
  $scope.$root.$broadcast('refresh');
});
1 Like

Hello,

How do you access the variableSrv . What class do you have to import?

Best regards,

just add variableSrv to your constructor and it will be injected. You can also just call this.refresh() from your controller to update with the new variable values after they’ve been set.

1 Like

I would like to access all the dashboard variables (not same as template variables) inside modules.ts and depending upon value of one of the variables, hide or show the panel. Any suggestions?
@torkel @kagey – seeking your help