Search code examples
cssangularjsng-style

AngularJS - how to replace colour for a box shadow with ng-style?


I am writing an app with Angular 1.5.

I am trying to put a box shadow on my element with a dynamic colour.

Here is what I have tried so far:

  <div
    item="item"
    ng-style="{ 'box-shadow': 5px 0px 0px 0px {{ item.colour }} inset; }"
    ng-repeat="item in vm.items">
</div>

The browser keeps throwing this error: Error: [$parse:lexerr] Lexer Error: Unexpected next character at columns 32-32 [#] in expression [{ 'box-shadow': 5px 0px 0px 0px #800000 inset; }].

item.colour is a string with a hex value in it.

I have also tried this:

ng-style="{ 'box-shadow': 5px 0px 0px 0px item.colour inset; }"

and it doesn't work either.

How can I write my ng-style expression for this case?


Solution

  • Within ng-style attribute you can write an expression that works very much like javascript, that is, you can concatenate string the same way javascript does.

    For example:

    ng-style="{ 'box-shadow': '5px 0px 0px 0px ' + item.colour + ' inset' }"
    

    UPDATE 1 Working snippet

    .box {
      width: 100px;
      height: 100px;
      background-color: grey;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.js"></script>
    <div ng-app ng-init="item = { colour: '#800000'}">
      <div class="box" ng-style="{ 'box-shadow': '5px 0px 0px 0px ' + item.colour + ' inset' }">
      </div>
    </div>