【问题标题】:Ng-style not working for backgroundNg 风格不适用于背景
【发布时间】:2017-01-22 12:18:25
【问题描述】:

我需要通过ng-style从配置对象设置元素的背景,但是由于某种未知原因我不能这样做,这对我来说真的很奇怪,我真的找不到原因。

我要配置的元素:

<div id="progress-l" ng-style="{ 'width': pblc.options.width, 'height': pblc.options.height, 'background': plbc.options.color }"></div>

pblc在这里代表控制器,我使用controllerAs选项

配置对象:

this.progressLOptions = {
    color: '#F0F3F4',
    width: '200px',
    height: '20px',
};

最奇怪的是设置了宽度和高度,在渲染的html中我看到了:

<div id="progress-l" ng-style="{ 'width': pblc.options.width, 'height': pblc.options.height, 'background': plbc.options.color }" style="width: 200px; height: 20px;">
</div>

我真的不知道 ng-style 怎么会这样工作。我找不到背景是否有问题?

【问题讨论】:

  • pblc.options 是什么,我看到你有 progressLOptions,你把范围变量名弄乱了吗?
  • @PankajParkar 不,我只是使用controllerAs 进行指令,如果是命名,高度和宽度也不会设置

标签: javascript html css angularjs ng-style


【解决方案1】:

更新的答案: 你有一个错字 - plbc.options.color 而不是 pblc.options.color

最可能的原因是plbc.options.color 未定义、为空、不在范围内或配置错误。当然,这是在没有语法错误的情况下。

尝试在模板中将其作为表达式输出 - {{plbc.options.color}} 并检查它。

【讨论】:

    【解决方案2】:

    我已经修改了你的代码,请看这个

        <div id="progress-l" ng-style="{ 'width': progressLOptions.width, 'height': progressLOptions.height, 'background': progressLOptions.color }" style="width: 200px; height: 20px;">
       </div>
    

    JS

       $scope.progressLOptions = {
        color: '#000',
         width: '200px',
        height: '20px',
       };  
    

    它正在工作。使用 $scope 而不是 this 或者如果你想要 this.progressLoptions 然后在 HTML 中使用

    <body ng-controller="somename as controllerName"> 
    and then access this using somename.functionName
    

    演示:https://jsbin.com/zihazi/edit?html,js,output

    【讨论】:

    • 谢谢你的回答,是正确的,但事实证明,我有一个错字
    • 太酷了!!这就是为什么我做了演示,你的逻辑是正确的,但在某个地方有一个错误..!反正总算解决了。干杯!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-14
    • 2019-03-30
    • 2019-07-27
    • 2011-09-05
    • 2017-02-13
    • 2020-09-15
    相关资源
    最近更新 更多