如何使用 ng-style 设置 div 宽度 [英] How to set div width using ng-style

查看:70
本文介绍了如何使用 ng-style 设置 div 宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 ng-style 动态设置 div 宽度,但它没有应用样式.代码如下:

<div style="width: 250px;overflow: scroll;"><div ng-style="myStyle">&nbsp;</div>

控制器:

var MyApp = angular.module('MyApp', []);var custController = MyApp.controller('custController', function ($scope) {$scope.myStyle="width:'900px';background:red";});

我错过了什么?

小提琴链接:小提琴

解决方案

ng-style 的语法并非如此.它接受键(属性名称)和值(它们应该采用的值,一个空字符串取消设置它们)的字典,而不仅仅是一个字符串.我想你想要的是这个:

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

然后在您的控制器中:

$scope.width = '900px';$scope.bgColor = '红色';

这保留了模板和控制器的分离:控制器保存语义值,而模板将它们映射到正确的属性名称.

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

<div style="width: 100%;" id="container_fform" ng-controller="custController">
    <div style="width: 250px;overflow: scroll;">
        <div ng-style="myStyle">&nbsp;</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

解决方案

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.

这篇关于如何使用 ng-style 设置 div 宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆