Home ng-class not working in AngularJS when defined with scope variable
Reply: 2

ng-class not working in AngularJS when defined with scope variable

billgajen
1#
billgajen Published in 2017-09-14 09:05:31Z

For my below code ng-class isn't working:

HTML

<div class="row-content" ng-controller="MainController">
  <div class="tabs">
    <div class="col-xs-6">
      <h3 ng-class="{selected: searchType == 'news'}">
        <a ng-click="SetSearchType('news')" 
           href="javascript:void(0)">Alumni News</a>
      </h3>
    </div>
    <div class="col-xs-6">
      <h3 ng-class="{selected: searchType == 'rss'}">
        <a ng-click="SetSearchType('rss')" 
           href="javascript:void(0)">Firm News</a>
      </h3>
    </div>
  </div>
</div>

AnjgularJS

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

app.controller('MainController', ['$scope', function($scope) {

    $scope.searchType = 'news';

    $scope.SetSearchType = function(type) {
        $scope.searchType = type;
    }
}]);
Aref Zamani
2#
Aref Zamani Reply to 2017-09-14 09:51:28Z

put your class in quotes ('')

<div class="row-content" ng-controller="MainController">
                <div class="tabs">
                    <div class="col-xs-6">
                        <h3 ng-class="{'selected': searchType == 'news'}">
                            <a ng-click="SetSearchType('news')" href="javascript:void(0)">Alumni News</a>
                        </h3>
                    </div>
                    <div class="col-xs-6">
                        <h3 ng-class="{'selected': searchType == 'rss'}">
                            <a ng-click="SetSearchType('rss')" href="javascript:void(0)">Firm News</a>
                        </h3>
                    </div>
                </div>
lin
3#
lin Reply to 2017-09-14 14:22:57Z

I think there is something wrong with your CSS styles or your $scope.selected param. Please check this runnable demo fiddle and carefully compare it with your solution:

View

<div class="row-content" ng-controller="MainController">
  <div class="tabs">
    <div class="col-xs-6">
      <h3 ng-class="{'selected': searchType == 'news'}">
        <a ng-click="SetSearchType('news')" 
           href="javascript:void(0)">Alumni News</a>
      </h3>
    </div>
    <div class="col-xs-6">
      <h3 ng-class="{'selected': searchType == 'rss'}">
        <a ng-click="SetSearchType('rss')" 
           href="javascript:void(0)">Firm News</a>
      </h3>
    </div>
  </div>
</div>

AngularJS

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

myApp.controller('MainController', function($scope) {
  $scope.searchType = 'news';

  $scope.SetSearchType = function(type) {
    $scope.searchType = type;
  }
});

CSS

.selected a {
  color:red;
}
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.304612 second(s) , Gzip On .

© 2016 Powered by cudou.com design MATCHINFO