最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - ng-class not overriding class as expected - Stack Overflow

programmeradmin0浏览0评论

I have a list of icons that are either "on" or "off" depending on boolean values in the $scope. I created two CSS classes -- clrOn and clrOff -- and they are only different colors. I am assigning all of the icons clrOff using class="" and then trying to override that with ng-class="" if the boolean is true.

Based on my research, this is what I have that should work. plunker

CSS FILE:

.clrOn { color: #333333; }
.clrOff { color: #DDDDDD; }

JS FILE:

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.attachments = 1;
});

HTML:

<body ng-controller="MainCtrl">
    <span class="clrOff" 
          tooltip="Attachments" 
          ng-class="{ 'clrOn' : app.attachments }">
          TEST
    </span>
  </body>

I have a list of icons that are either "on" or "off" depending on boolean values in the $scope. I created two CSS classes -- clrOn and clrOff -- and they are only different colors. I am assigning all of the icons clrOff using class="" and then trying to override that with ng-class="" if the boolean is true.

Based on my research, this is what I have that should work. plunker

CSS FILE:

.clrOn { color: #333333; }
.clrOff { color: #DDDDDD; }

JS FILE:

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.attachments = 1;
});

HTML:

<body ng-controller="MainCtrl">
    <span class="clrOff" 
          tooltip="Attachments" 
          ng-class="{ 'clrOn' : app.attachments }">
          TEST
    </span>
  </body>
Share Improve this question edited Jul 30, 2014 at 13:32 Huangism 16.4k7 gold badges50 silver badges75 bronze badges asked Jul 30, 2014 at 13:23 jgravoisjgravois 2,57910 gold badges44 silver badges67 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

First thing, ng-class="{ 'clrOn' : app.attachments }" is not picking up the attachments variable since it's declared directly on scope and not on scope.app so change that to ng-class="{ 'clrOn' : attachments }".

Second, ng-class will not override any existing class attributes, but add to them so your span will be left with having both classes applied to it. If you dont want to have both classes assigned you'll need to declare them both using ng-class.

发布评论

评论列表(0)

  1. 暂无评论