如何将 ng-style 与 !important 一起使用?

Nis*_*ant 8 css angularjs ng-style

标签按钮已分配了光标 css。我想根据 is_active 值覆盖光标 css 以禁用按钮。is_active 的值可能为 0 或 1。以下是 js/html 代码,请告诉我将光标 css 应用于按钮的正确方法。

$scope.ngStyleDisabled = function(status) {
  if (status == 1) {
    return {};
  } else if (status == 0) {
    return '{\'cursor\':\'not-allowed !important\',\'pointer-events\':\'none\'}';
  }
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<button ng-style="{{ngStyleDisabled(item.is_active)}}">Action Button</button>
Run Code Online (Sandbox Code Playgroud)

Sen*_*mes 6

剧透警告:所有说 ng-style 不支持的人!important都是*错误的!

*嗯,有点错误。即,虽然它绝对支持开箱即用,但您可以通过以下解决方法强制它(为了方便起见,此处进行了简化):

<elem data-ng-attr-style="{{ 'color: ' + your_color_var + ' !important' }}"></elem>
Run Code Online (Sandbox Code Playgroud)

例如

<span data-ng-attr-style="{{ 'color: indigo !important' }}"></span>
Run Code Online (Sandbox Code Playgroud)

等等...所以我们必须使用黑客才能开始!important工作!?!这就像……双重黑客!!!或者双双十字!!三重十字?!?

哈哈。


mue*_*hdo 1

根据文档,您的表达式需要是一个对象:

表达式的值是一个对象,其键是 CSS 样式名称,值是这些 CSS 键的对应值。

尝试返回一个对象而不是字符串(使用引号,因为 CSS 属性可能不是有效的键):

$scope.ngStyleDisabled = function(status) {
  if (status == 1) {
    return {};
  } else if (status == 0) {
    return {
      'cursor': 'not-allowed', // !important does not work in ng-style
      'pointer-events': 'none'
    };
  }
}
Run Code Online (Sandbox Code Playgroud)

另外,请省略模板中的花括号:

<button ng-style="ngStyleDisabled(item.is_active)">Action Button</button>
Run Code Online (Sandbox Code Playgroud)

JSFiddle显示了如何将属性应用于按钮。

注意 根据此问题和此 GitHub问题,指令!important中不支持该关键字ng-style。您可以在链接后面找到解决方法。