Search code examples
javascripthtmlcssangularjsng-style

Can I use data from API call in Angular ng-style directive?


I'm attempting to set the border color and box-shadow color around images pulled from an API based on other data from the API. Basically, I want these colors to be loaded dynamically. Through research I know that ng-style is the way to go and I'm 90% of the way there. I'm having problems using data returned from my API call in the CSS of ng-style. See below:

relevant html:

<a href="{{item.link}}" target="_blank">
    <img src="{{item.images.standard_resolution.url}}" alt="" class="img-responsive" ng-style="homeColors" id="image">
</a>

relevant code from Angular controller:

Stadia.get($scope.id).success(function(response) {
    $scope.shadow = response.prim_hex;
    $scope.border = response.sec_hex;

    $scope.homeColors = {
        "border": "2px solid response.prim_hex",
        "box-shadow": "3px 3px 7px response.sec_hex",
        "margin": "6px",
        "padding": "0"
    }

I'm stumbling over how to get the API results (response.prim_hex and response.sec_hex) into my CSS object, homeColors, so they are loaded in my ng-style directive.


Solution

  • You have the variables' names being used as part of the string, rather than having them evaluated and appended. Try the below:

    Stadia.get($scope.id).success(function(response) {
        $scope.shadow = response.prim_hex;
        $scope.border = response.sec_hex;
    
        $scope.homeColors = {
            "border": "2px solid " + $scope.shadow,
            "box-shadow": "3px 3px 7px " + $scope.border,
            "margin": "6px",
            "padding": "0"
        }