How to set div width using ng-style

后端 未结 2 1384
时光取名叫无心
时光取名叫无心 2020-12-07 18:00

I am trying to set the div width dynamically using ng-style but it is not applying the style. Here is the code:

相关标签:
2条回答
  • 2020-12-07 18:49

    ngStyle accepts a map:

    $scope.myStyle = {
        "width" : "900px",
        "background" : "red"
    };
    

    Fiddle

    0 讨论(0)
  • 2020-12-07 18:59

    The syntax of ng-style is not quite that. It accepts a dictionary of keys (attribute names) and values (the value they should take, an empty string unsets them) rather than only a string. I think what you want is this:

    <div ng-style="{ 'width' : width, 'background' : bgColor }"></div>
    

    And then in your controller:

    $scope.width = '900px';
    $scope.bgColor = 'red';
    

    This preserves the separation of template and the controller: the controller holds the semantic values while the template maps them to the correct attribute name.

    0 讨论(0)
提交回复
热议问题