当使用范围变量定义时,ng-class在AngularJS中不起作用

时间:2017-09-14 09:05:32

标签: javascript html css angularjs

我的以下代码ng-class无效:

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;
    }
}]);

2 个答案:

答案 0 :(得分:1)

我认为您的CSS样式或$scope.selected参数存在问题。请检查此可运行 demo fiddle 并仔细将其与您的解决方案进行比较:

视图

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

答案 1 :(得分:0)

将您的课程用引号(&#39;&#39;)

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