user1227793 user1227793 - 1 month ago 17
CoffeeScript Question

ng-class does not change class unless I refresh the page

I'm using ng-class in my view to change the class of and element and it works fine on page load. Here is my code:

<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>


As you can see, it takes the second currency from the URL and compares it with another to decide which class it should assign to my li element.

The trouble now is that when someone clicks on the link and the URL changes, the class assigned does not change. Any idea how I can get the class assigned by ng-class to change when the

Answer

Try this,

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;  
  }
});
.active {
  background-color: green;
}
<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>