CSS 如何使用 ng-style 设置 div 宽度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20287241/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to set div width using ng-style
提问by user3049403
I am trying to set the div width dynamically using ng-style
but it is not applying the style. Here is the code:
我正在尝试使用动态设置 div 宽度,ng-style
但它没有应用样式。这是代码:
<div style="width: 100%;" id="container_fform" ng-controller="custController">
<div style="width: 250px;overflow: scroll;">
<div ng-style="myStyle"> </div>
</div>
</div>
Controller:
控制器:
var MyApp = angular.module('MyApp', []);
var custController = MyApp.controller('custController', function ($scope) {
$scope.myStyle="width:'900px';background:red";
});
What am I missing?
我错过了什么?
Fiddle link: Fiddle
小提琴链接:小提琴
回答by musically_ut
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 unsetsthem) rather than only a string. I think what you want is this:
的语法ng-style
并非如此。它接受键(属性名称)和值(它们应该采用的值,空字符串取消设置它们)的字典,而不仅仅是一个字符串。我想你想要的是这个:
<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.
这保留了模板和控制器的分离:控制器保存语义值,而模板将它们映射到正确的属性名称。