如何通过函数获取ng-style的多css规则?

2024-02-15

我需要将多 css 规则应用于角度表单模板中的 html 标签。

<div class="form-control" id="data.objectStyle"  
  ng-model="data.type" 
  ng-style="getStyle(data.objectStyle)">
{{data.objectStyle.title}}
</div>

控制器中的 getStyle 函数:

$scope.getStyle = function (taskType) {
    return {
         background-color:taskType.backColor,
         color: taskType.color,
         font-size:taskType.fontSize,
         font-family:taskType.font
    }
)};

任务类型对象:

{
    backColor:'#006',
    color:'#56DA',
    fontSize:12,
    font:'New Times Roman'
}

The getStyle函数不返回样式!该怎么办?


EDIT

The docs https://docs.angularjs.org/api/ng/directive/ngStyle指定您需要将键括在引号中,这样它们就不是无效的 JSON 对象键:

return {
     "background-color": taskType.backColor,
     "color": taskType.color,
     "font-size":taskType.fontSize,
     "font-family":taskType.font
}

旧答案(不使用 ng 风格)

虽然我从未使用过ng-style https://docs.angularjs.org/api/ng/directive/ngStyle,它似乎不带物体。相反,它相当于 ng-class,但适用于单一样式。

尝试将您的功能更改为:

$scope.getStyle = function (taskType) {

        return {
         "background-color:"+taskType.backColor+
         ";color:"+ taskType.color+
         ";font-size:"+taskType.fontSize+
         ";font-family:"+taskType.font+";";
    }
)};

以及使用带有绑定的常规样式标签的 html:

<div class="form-control" id="data.objectStyle"  
ng-model="data.type" style="{{getStyle(data.objectStyle)}}">
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何通过函数获取ng-style的多css规则? 的相关文章