Search code examples
javascriptcssangularjsangularjs-ng-repeatng-style

AngularJS and ng-style with ng-repeat


I have a problem using ng-style with ng-repeat.

This is my code:

<div style="display:table-row" ng-repeat="row in Data.Communications" id="{{row.Guid}}">
    <div style="display:table-cell;">
      <img ng-src="{{row.Path}}" ng-show="row.Path" ng-style="row.Style" />
      <i class="{{row.Icon}}" ng-show="row.Icon" ng-style="row.Style"></i>
    </div>
</div>

This is the JSON (Loaded server-side from a DB):

$scope.Data: {"LastUpdate":"23/03/2016 11:45","Communications":[{"Guid":"2","Path":null,"Icon":"fa fa-warning","Style":"{'color':'#ffff00'}"},{"Guid":"1","Path":null,"Icon":"fa fa-warning","Style":"{'color':'#ffff00'}"},{"Guid":"3","Path":"/images/blink_yellow.gif","Icon":null,"Style":"{'width':'15px', 'height':'15px'}"}]}

The "Style" is not applied to my elements. Could someone help me to solve this problem?


Solution

  • Basically you have strigified JSON, do parse it before assign it to ng-style

    ng-style="doParseToJson(row.Style)"
    

    Code

    $scope.doParseToJson = function(style){
       return JSON.parse(style);
    }
    

    Also make sure response should be wrap with " double qoutes instead of single quotes like '{"color":"#ffff00"}' to keep it valid for parsing the JSON.