从角度控制器有条件地加载 css

Ben*_*ers 2 javascript css accessibility angularjs

我正在努力使我的网站更易于访问。我遇到的问题之一是文本/背景对比度。根据规范,可以放置一个启用高对比度模式的高对比度开关。为了满足这个要求,我想在我的网站上放置一个按钮或开关,当它被激活时,会触发一个功能,该功能扫描文档中的实例background:low-contrast并将该属性替换为background:high-contrast.

我已经完成了工作ng-class="{'high-contrast':highContrast}"

<button 
    ng-controller="HighContrastController" 
    ng-click="$root.highContrast=!$root.highContrast" 
    class="high-contrast-switch">
  <i class="fa text-white fa-adjust">
    <span class="sr-only">High Contrast Mode</span>
  </i>
</button> 
Run Code Online (Sandbox Code Playgroud)

function HighContrastController($rootScope) {
  $rootScope.highContrast = false;
}
Run Code Online (Sandbox Code Playgroud)

但我想我更愿意在控制器中完成这一切,这将使我能够在全局范围内对所有视图应用高对比度,而不会使逻辑混乱。

我可以做到的一种方法是忘记high-contrast课程,然后申请lightdark课程。当通过控制器加载时,highcontrast.css 会将高对比度颜色应用于这些类。有没有角度的方法来做到这一点,还是我应该依靠常规的 javascript 来加载 highcontrast.css?

fik*_*tra 5

在某些根元素(例如 body)上设置一个带有 ng-class 的 'highContrast' 类。然后,在您的 css 中,根据此类应用单独的 css 规则。

在 css 中更改颜色仍然很麻烦,但至少你不会把你的控制器、rootscope 和 html 弄得一团糟。您可以通过使用 less 或 sass 来保持您的 css 相对干净,这肯定有助于保持简单,例如通过使用变量。

var module = angular.module('myApp', []);
module.controller('accessibilityController', function() {});
module.controller('someController', function() {});
module.controller('someOtherController', function() {});
Run Code Online (Sandbox Code Playgroud)
.mainContent {
  color: blue;
}
.highContrast .mainContent {
  color: red;
}
.highContrast .custom {
  color: green;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-class="{'highContrast': highContrast}" ng-controller="accessibilityController">
  <button ng-click="highContrast = !highContrast">Switch colour</button>
  <div class="mainContent">
    <div ng-controller="someController">This simulates a partial view</div>
    <div ng-controller="someOtherController">This also simulates a partial view</div>
    <div class="custom">Customize accessibility by overriding css rules</div>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)