Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Angular的ng-style用法 #35

Closed
Wscats opened this issue Jun 28, 2016 · 0 comments
Closed

Angular的ng-style用法 #35

Wscats opened this issue Jun 28, 2016 · 0 comments
Labels

Comments

@Wscats
Copy link
Owner

Wscats commented Jun 28, 2016

DEMO的效果如下
image
ng-style属性值需要传入对象
对象由CSS属性和值注册,即key=>value键值对
对象的格式如同DEMO中的这个对象

{
                "color": "#FFF",
                "background-color": "#FF7E4F",
                "font-size": "60px",
                "padding": "20px"
            }

全部的代码如下

<!DOCTYPE html>
<html ng-app="wsscat" ng-controller="catCtrl">
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0,user-scalable=no">
        <title></title>
        <script type="text/javascript" src="ng.js"></script>
    </head>

    <body>
        <div ng-style="myStyle">Wsscat</div>
    </body>
    <script>
        var app = angular.module("wsscat", []);
        app.controller("catCtrl", function($scope) {
            $scope.myStyle = {
                "color": "#FFF",
                "background-color": "#FF7E4F",
                "font-size": "60px",
                "padding": "20px"
            }
        });
    </script>
</html>

有时候我们需要在DOM中直接把对象写在ng-style里面,里面还要绑定一些$scope的数据
那么我们可以这样,注意对象大括号里面用单引号,用双引号是无法运行的

<div ng-style="{
            'color': '#FFF',
            'background-color': '#FF7E4F',
            'font-size': '60px',
            'padding': '20px'
        }">Wsscat</div>

然后我们再复杂一点,绑定$scope给视图的数据,我们就可以再这样写

<div ng-style="{
            'color': '#FFF',
            'background-color': '#FF7E4F',
            'font-size': '60px',
            'padding': '{{padding}}'
        }">Wsscat</div>

在控制器定义好padding就可以了,这种情况在某些情况是会运用到的
$scope.padding = "30px";

@Wscats Wscats added the notes label Jun 28, 2016
@Wscats Wscats closed this as completed Aug 22, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant