如何在ng-click上切换角度js中的类

时间:2015-04-23 11:38:48

标签: angularjs

我想点击一下课程,请找到我的下面的代码。

<li class="dropdown" data-ng-class="sign-open">
  <a href="" class="dropdown-toggle" data-ng-click="signToogle()">Sign In <b class="caret"></b></a>
  <div class="dropdown-menu" style="padding: 15px;">
    <form action="#" method="post" accept-charset="UTF-8" class="form-menu">
      <input id="user_username" type="text" name="user[username]" size="33" placeholder="Username">
      <input id="user_password" type="password" name="user[password]" size="33" placeholder="Password">
      <label class="checkbox muted hidden-tablet">
        <input type="checkbox">Remember Me</label>
      <input class="btn span3" type="submit" name="commit" value="Sign In">
    </form>

  </div>
</li>


//sign in show-hide
$scope.signToogle = function () {
    if ($scope.sign-open === "")
        $scope.class = "open";
    else
        $scope.class = "";
}

这个js funciton将addclass打开,所以如果ul有开放类作为它的父级,那么它将是可见的。 但是我不知道我如何能够如果点击一次然后是真的,那么附加如果再次点击语句为false并且类将被删除

2 个答案:

答案 0 :(得分:5)

您可以使用ng-class

<div ng-class="{active: is_active}">Some div</div>

<button ng-click="is_active = !is_active" ng-init="is_active=false">Click to toggle</button>

点击

时设置或重置$scope.is_active

答案 1 :(得分:2)

&#13;
&#13;
var app = angular.module('app', []);

app.controller('Main', function($scope) {
  $scope.isOpen = false;
});
&#13;
.item span {
  display: none;
}
.item.close span.show-on-close {
  display: block;
}
.item.open span.show-on-open {
  display: block;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app">

  <div ng-controller="Main">
    <pre>isOpen: {{isOpen | json}}</pre>
    <span class="item" ng-class="{'open':isOpen, 'close':!isOpen}">
      <span class="show-on-open">open</span>
    <span class="show-on-close">close</span>
    </span>

    <button ng-click="isOpen = !isOpen">Toggle</button>
  </div>
</div>
&#13;
&#13;
&#13;

  

注意:JavaScript中的变量不能包含短划线字符   所以将您的$scope.sign-open重命名为$scope.signOpen

你甚至不必在控制器中定义一个功能,你可以这样做:

<span ng-class="{'open':!signOpen, '':signOpen}"></span>

单击处理程序上的

<button ng-click="signOpen = !signOpen">toggle</button>