Andrew Ducker
Andrew Ducker

Reputation: 5490

How do I set multiple attributes from a single function call, using Angular?

I want to be able to switch in one of three images (an up arrow, down arrow, or square) depending on whether a particular number has gone up, gone down, or stayed the same.

I have a function call that allows me to check this - but I want to set both the img src and the title attribute based on it.

At the moment this means calling the function twice, once for each attribute. Which isn't a solution I'm happy with.

Is there any way to call the function once and then set both attributes based on the response?

Existing code:

<img src="{{trendImage(metric.scoreCardPassed, metric.scoreCardTrend).image}}" 
   title="{{trendImage(metric.scoreCardPassed, metric.scoreCardTrend).description}}">

Upvotes: 1

Views: 842

Answers (2)

Bogdan Rybak
Bogdan Rybak

Reputation: 2117

One way of solving this could be also using ngInit to initialize a new scope variable. This directive takes in angular expressions.

<img ng-init="trendDetails = trendImage(metric.scoreCardPassed, metric.scoreCardTrend)" ng-src="{{trendDetails.image}}" title="{{trendDetails.description}}">

Upvotes: 2

jkjustjoshing
jkjustjoshing

Reputation: 3630

Nope, you can't set 2 attributes with 1 function call. You have 3 options (that I can see) to solve this:


Option 1 - Make sure that trendImage is a lightweight function so it doesn't matter how many times you call it.


Option 2 - Bind the src and title to a scope variable:

<img ng-src="metric.image" title="{{metric.description}}" />

and call trendImage in a $scope.$watch method:

$scope.$watch(function() {return trendImage(metric);}, function(newValue) {
  $scope.metric = newValue;
});

but I presume that won't work for you because you probably have a bunch of these elements on the page


Option 3 - If the image could only have 3 possible values, put them all there, and switch between them with an ng-switch or ng-if:

<img ng-if="trendImage(metric.scoreCardPassed, metric.scoreCardTrend).image == 'up-arrow.png'" src="up-arrow.png" title="Up Arrow" />
<img ng-if="trendImage(metric.scoreCardPassed, metric.scoreCardTrend).image == 'down-arrow.png'" src="down-arrow.png" title="Down Arrow" />
<img ng-if="trendImage(metric.scoreCardPassed, metric.scoreCardTrend).image == 'square.png'" src="square.png" title="Square" />

(or something like that - in this case $scope.trendImage wouldn't need to return an object, just 1 of 3 possible values)


Based on what you asked, Option 3 probably is the best option, followed by option 1.

Upvotes: 1

Related Questions