我正在尝试工作如何使用ngClick添加类。我已将代码上传到plunker Click here上。查看 angular 文档,我不知道应该怎么做。以下是我的代码片段。有人可以指引我正确的方向
<div ng-show="isVisible" ng-class="{'selected': $index==selectedIndex}" class="block"></div>
Controller
var app = angular.module("MyApp", []);
app.controller("subNavController", function ($scope){
$scope.toggle = function (){
$scope.isVisible = ! $scope.isVisible;
};
$scope.isVisible = false;
});
最佳答案
您只需要将变量绑定(bind)到指令“ng-class”,然后从 Controller 进行更改即可。这是如何执行此操作的示例:
var app = angular.module("ap",[]);
app.controller("con",function($scope){
$scope.class = "red";
$scope.changeClass = function(){
if ($scope.class === "red")
$scope.class = "blue";
else
$scope.class = "red";
};
});
.red{
color:red;
}
.blue{
color:blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="ap" ng-controller="con">
<div ng-class="class">{{class}}</div>
<button ng-click="changeClass()">Change Class</button>
</body>
这是在jsFiddle上工作的示例