AngularJS和带有ng重复的ng样式

AngularJS and ng-style with ng-repeat

本文关键字:ng 样式 AngularJS      更新时间:2023-09-26

我在使用带有ng repeat的ng样式时遇到问题。

这是我的代码:

<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>

这是JSON(从数据库加载的服务器端):

$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'}"}]}

"样式"未应用于我的元素。有人能帮我解决这个问题吗?

基本上您已经删除了JSON,在将其分配给ng-style 之前先进行解析

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

代码

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

还要确保响应应该用"双引号包装,而不是像'{"color":"#ffff00"}'这样的单引号,以保持其对解析JSON有效。