除非我刷新页面,否则ng-class不会更改类

时间:2016-10-13 13:35:26

标签: javascript angularjs coffeescript

我在视图中使用ng-class来更改类和元素,它在页面加载时工作正常。这是我的代码:

<ul>
  <li ng-class="'{{account.currency}}' == '{{currency}}' ? 'active': 'inactive'" ng-repeat="account in accounts" bind="accounts">
    <a href="#/deposits/{{account.currency}}" ng-click="changeClass('{{account.currency}}', '{{currency}}')">
    {{currency}}
    </a>
  </li>
<ul>

正如您所看到的,它从URL中获取第二种货币并将其与另一种货币进行比较,以确定它应分配给我的li元素的类。

现在的麻烦是当有人点击链接并且URL发生变化时,分配的类不会改变。知道怎样才能让ng-class分配的类在

时改变

3 个答案:

答案 0 :(得分:3)

您不需要为此调用函数,这可以很容易地实现内联

尝试这样:

<li ng-class="{'active' : account.currency == currency, 'inactive': 
account.currency != currency}">

OR

<li ng-class="{true: 'active', false: 'inactive'}[account.currency == currency]">

如果您使用的是角度v.1.1.4 +

<li ng-class="account.currency == currency ? 'active': 'inactive'}">

答案 1 :(得分:2)

制作ng-class= {'active': account.currency === currency}

在css文件中

你应该有.active{}类。让非活动类成为默认行为。

P.S Dhaval的答案也应该起作用

答案 2 :(得分:2)

试试这个,

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

app.controller('myctrl', function() {
  var vm = this;
  vm.accounts = [{
    currency: 'Doller'
  }, {
    currency: 'Pound'
  }, {
    currency: 'Euro'
  }];
  
  vm.changeClass = function(account) {
    vm.active = account.currency;  
  }
});
&#13;
.active {
  background-color: green;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body>
  <div ng-app="app" ng-controller="myctrl as ct">
    <ul>
      <li ng-class="{'active': ct.active === account.currency}" ng-repeat="account in ct.accounts">
        <a href="#" ng-click="ct.changeClass(account)">
          {{account.currency}}
        </a>
      </li>
    </ul>
  </div>

</body>
&#13;
&#13;
&#13;