Angularjs addclass?

时间:2016-02-20 20:14:20

标签: jquery angularjs

我想将其转换为jQuery ....请帮助:

$('.toggle').on('click', function() {
  $('.container').addClass('active');
});

$('.close').on('click', function() {
  $('.container').removeClass('active');
});

这是我的index.html ..:

<div class="container">
  <div class="card"></div>
  <div class="card">
    <h1 class="title">Login</h1>
    <form>
      <div class="input-container">
        <input type="text" id="Username" required="required"/>
        <label for="Username">Username</label>
        <div class="bar"></div>
      </div>
      <div class="input-container">
        <input type="password" id="Password" required="required"/>
        <label for="Password">Password</label>
        <div class="bar"></div>
      </div>
      <div class="button-container">
        <button><span>Go</span></button>
      </div>
      <div class="footer"><a href="#">Forgot your password?</a></div>
    </form>
  </div>
  <div class="card alt">
    <div class="toggle" ng-click="enabled=true"></div>
    <h1 class="title">Register
      <div class="close"></div>
    </h1>
    <form>
      <div class="input-container">
        <input type="text" id="Username" required="required"/>
        <label for="Username">Username</label>
        <div class="bar"></div>
      </div>
      <div class="input-container">
        <input type="password" id="Password" required="required"/>
        <label for="Password">Password</label>
        <div class="bar"></div>
      </div>
      <div class="input-container">
        <input type="password" id="Repeat Password" required="required"/>
        <label for="Repeat Password">Repeat Password</label>
        <div class="bar"></div>
      </div>
      <div class="button-container">
        <button><span>Next</span></button>
      </div>
    </form>
  </div>
</div>

我已经尝试过ng-class但似乎没有工作......我不明白如何将上面的jQuery代码转换为angular。帮助将不胜感激..

2 个答案:

答案 0 :(得分:1)

由于您已经切换变量enabled,所以您需要的是:

<div class="container" ng-class="{active: enabled}">

然后还在close元素

中切换相同的变量

答案 1 :(得分:1)

以下是Angular的ng-clickng-class指令的简单演示:http://plnkr.co/edit/JJXs5BPB2e5owIYReFxO?p=preview

模板中的Html:

<div ng-controller="showcaseCtrl">
  <button ng-click="doStuff()">doStuff</button>
  <div class="container" ng-class="{'active': isActive}">this is container</div>
</div>
控制器中的

JS

 $scope.doStuff = function(){
   $scope.isActive = !$scope.isActive;
 }

.toggle类中没有必要触发事件的元素。它的作用是在控制器中调用doStuff函数。该函数切换isActive范围变量的值。 并且ng-class块上的.content指令会读取变量更改 - 如果添加了真正的类active;