AngularJS:如何为所有元素设置样式属性?

时间:2015-01-27 22:41:04

标签: css angularjs

我有一个我正在处理的表单页面,基本的AngularJS结构正在运行。当用户选择特定字体时,我希望所有页面元素都更改为该字体。在我的样式表中,我使用“*”选择器,但我无法弄清楚如何通过Angular更新它。我已经附上了下面的基本页面结构代码(请注意,该页面包含的元素多于此但我删除了除了H1之外的所有元素)。有什么想法吗?

<!doctype html>
<html ng-app="theapp">
<head>
    <title>App</title>
    <style type="text/css">
        * {
            font-family: sans-serif;
            font-size: 12pt;
        }
    </style>
</head>
<body ng-controller="FormController as form">
    <h1>Hello</h1>
    <form name="theForm">
        <select ng-model="font" ng-options="font.face for font in fonts"></select>
    </form>
    <script type="text/javascript" src="js/angular.min.js"></script>
    <script type="text/javascript">
        (function () {
            angular.module("theapp", [])
                .controller("FormController", ["$scope", function ($scope) {
                    $scope.fonts = [
                        { face: "sans-serif" },
                        { face: "Arial" },
                        { face: "Tahoma" },
                        { face: "Trebuchet MS" },
                        { face: "Verdana" },
                        { face: "serif" },
                        { face: "Times" },
                        { face: "Georgia" },
                        { face: "monospace" },
                        { face: "Courier" }
                    ];
                    $scope.font = $scope.fonts[0];
                }]);
        })();
    </script>
</body>
</html>

3 个答案:

答案 0 :(得分:1)

您可以在标记中使用ng-style并将其与scope.font变量相关联。

查看文档:{​​{3}}

我还没有尝试过,但您可以在div body下添加<div ng-style="style">$scope.style = {"font-family": $scope.font}在控制器中添加{{1}}。

答案 1 :(得分:1)

style="font-family:{{font.face}}"添加到body标记中。 我做了plunkr to demonstrate

答案 2 :(得分:0)

感谢[orange]和[nilsK]的建议。 两者都是好主意,但仍然不能满足我的需求。 最后,我决定只使用jQuery来更新$(&#34; *&#34;)。css()属性。 (我们已经在使用jQuery,所以我不会不必要地引入另一个JS库。) 这正是我所需要的,并且不会使代码复杂化。 再次感谢! :)

相关问题