【问题标题】:How to use ng-style with !important?如何将 ng-style 与 !important 一起使用?
【发布时间】:2015-12-12 16:26:06
【问题描述】:

标签按钮已经分配了光标 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\'}';
  }
}
<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>

【问题讨论】:

    标签: css angularjs ng-style


    【解决方案1】:

    ng-style 不支持!important

    所以另一种方法是使用ng-class而不是ng-style,它会解决问题。

    如果您想专门使用ng-style,请尝试在 html 本身中编写 - 请不要尝试在任何函数中编写。

    【讨论】:

      【解决方案2】:

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

      *嗯,有点不对。 IE。虽然它确实支持开箱即用,您可以使用the following workaround 强制它(为方便起见,此处已简化):

      <elem data-ng-attr-style="{{ 'color: ' + your_color_var + ' !important' }}"></elem>
      

      例如

      <span data-ng-attr-style="{{ 'color: indigo !important' }}"></span>
      

      等等...所以我们必须使用 hack 来让 !important 工作!?!这就像……双 破解!!!还是双双交叉!!三叉戟?!?

      哈哈。

      【讨论】:

        【解决方案3】:

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

        表达式,它评估一个对象,其键是 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'
            };
          }
        }
        

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

        <button ng-style="ngStyleDisabled(item.is_active)">Action Button</button>
        

        这个JSFiddle 显示了属性是如何应用于按钮的。

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

        【讨论】:

        • 尝试了返回结果为
        • 这不是你想要的吗?
        • 返回的值是双引号而不是单引号。
        • 如果您检查 JSFiddle,您可以看到属性已按照您的要求应用于按钮。有什么问题?
        【解决方案4】:

        https://github.com/angular/angular.js/issues/5379 中提到的最优雅的解决方法对我有用!

        例子(用jade/pug写的):

        a#share-test-link.item(ng-show="iAmTeamCreator()", href="", data-ng-attr-style="{{iAmTeamCreator() && 'display: block!important' || ''}}")

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-07-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-12-04
          • 2019-11-06
          相关资源
          最近更新 更多