【问题标题】:ng-class can't apply css class to elementng-class 不能将 css 类应用于元素
【发布时间】:2016-12-15 13:09:08
【问题描述】:

我的代码中某处有这个 div。

<div ng-class="className" >{{className}}</div>

有时我会通过 ng-click 调用 changeClass 函数来更改此 div 的类。

     $scope.changeClass = function(){
          console.log($scope.className)
              if ($scope.className === "expand-icon")
                 $scope.className = "expand-icon.expanded";
              else
                 $scope.className = "expand-icon";
  };

我可以看到由于 console.log 的类更改,并且页面上输出了 {{className}}。但是似乎没有应用 css 类。

实际上是一个“+”号,需要变成一个带有动画的“-”。这是css:

 /* + button */

.expand-icon {
  height: 32px;
  width: 32px;
  position: relative;
}
.expand-icon::before, .expand-icon::after {
  content: " ";
  width: 32px;
  height: 6px;
  background-color: #fff;
  display: block;
  position: absolute;
  top: 50%;
  left: 50%;
  transition: all 0.15s cubic-bezier(.42, 0, .58, 1);
  opacity: 1;
  border-radius: 2px;
}
.expand-icon::before {
  transform: translate(-50%, -50%) rotate(90deg);
}
.expand-icon::after {
  transform: translate(-50%, -50%);
}

.expand-icon {
  height: 32px;
  width: 32px;
  position: relative;
}
.expand-icon.expanded::before {
  transform: translate(-50%, -50%) rotate(0deg);
}
.expand-icon.expanded::after {
  transform: translate(-50%, -50%) rotate(-90deg);
  opacity: 0;
}

因此应用了 expand-icon 但 expand-icon.expanded 没有任何影响,因为我正在使用这个 ng-class 技巧。知道为什么吗?

【问题讨论】:

标签: javascript angularjs frontend


【解决方案1】:

您应该用空格替换点:$scope.className = "expand-icon expanded";

或者更好,使用ng-class的另一种表示法:

// probably rename it to something like $scope.toggleExpanded()
$scope.changeClass = function(){
    $scope.expanded = !$scope.expanded;
};

在你的 html 中:

<div class="expand-icon"
     ng-class="{ expanded: expanded }">{{className}}</div>

这将始终应用您的expand-icon 类,并且仅当$scope.expanded 属性为真时才应用expanded 类。

【讨论】:

    【解决方案2】:

    ng-class="className" 用于表达。例如:ng-class="{classNam:true}"

    在这种情况下,您可以这样做:class="{{className}}"

    【讨论】:

      【解决方案3】:

      试试这个

      <div class="{{className}}">{{className}}</div>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-12-31
        • 2014-04-20
        • 1970-01-01
        • 1970-01-01
        • 2015-12-13
        • 2017-10-04
        • 2019-06-22
        • 2016-10-25
        相关资源
        最近更新 更多