使用ng-click来存储和调用类

时间:2019-05-06 17:23:18

标签: css angularjs

我已经实现了ng-click来在两个 css 类之间切换<div>标签。在此示例中,“打开”和“关闭”

默认使用'off'类。

我觉得我应该使用一个布尔值来跟踪是否单击了它(是/否),但是不确定如何或在哪里实现。还是有更短的方法?

var app = angular.module("myApp", []);

app.controller("clickToggle", function($scope) {

  $scope.class = "off";

  $scope.changeClass = function() {
    if ($scope.class === "off")
      $scope.class = "on";
    else
      $scope.class = "off"
  };

});
.off {
  border: 1px solid black;
  background-color: white;
  box-sizing: border-box !important;
  border-radius: 200px !important;
  font: 30px 'Roboto';
  font-weight: 400;
  padding: 10px, 10px, 10px, 10px;
  color: black;
  text-align: center;
  width: 80px;
  height: 80px;
  display: inline-block;
  float: left;
  overflow: hidden;
  line-height: 80px;
}

.on {
  border: 1px solid black;
  background-color: blue;
  box-sizing: border-box !important;
  border-radius: 200px !important;
  font: 30px 'Roboto';
  font-weight: 400;
  padding: 10px, 10px, 10px, 10px;
  color: black;
  text-align: center;
  width: 80px;
  height: 80px;
  display: inline-block;
  float: left;
  overflow: hidden;
  line-height: 80px;
}

.circle:hover {
  font-weight: 400;
  background: #9fa8da;
  color: #f7f3eb;
  z-index: 9999;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js"></script>
<div ng-app="myApp" ng-controller="clickToggle">

  <div class="circle" ng-class="class" ng-click="changeClass()">1</div>

</div>

1 个答案:

答案 0 :(得分:0)

如果默认使用 .off 类,则可以将默认样式应用于.circle。 之后,您只需点击即可打开和关闭.on

angular.module("myApp", [])
.controller("clickToggle",['$scope', function($scope) {
  $scope.changeClass = function() {
    $scope.isActive = !$scope.isActive;
  };
}]);
.circle {
  border: 1px solid black;
  background-color: white;
  box-sizing: border-box !important;
  border-radius: 200px !important;
  font: 30px 'Roboto';
  font-weight: 400;
  padding: 10px, 10px, 10px, 10px;
  color: black;
  text-align: center;
  width: 80px;
  height: 80px;
  display: inline-block;
  float: left;
  overflow: hidden;
  line-height: 80px;
}

.on {
  background-color: blue;
}

.circle:hover {
  background: #9fa8da;
  color: #f7f3eb;
  z-index: 9999;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js"></script>
<div ng-app="myApp" ng-controller="clickToggle">

  <div class="circle" ng-class="{'on': isActive}" ng-click="changeClass()">1</div>

</div>