简体   繁体   中英

Angular ngClass Not Evaluating to Class Names

I am trying to create a custom class name using ng-class. I want to combine the values of two scope variables to create that name. Here's my code:

HTML:

<body ng-app="programApp" ng-controller="programController">
  <div ng-class="{quarter+number}">This should have a class of '.quarter12'</div>
</body>

JS:

angular.module('programApp', [
    'programApp.controllers',
]);
angular.module('programApp.controllers', [])
    .controller('programController', ['$scope', '$filter', '$http', 
    function($scope, $filter, $http){
      $scope.quarter = 'quarter';
      $scope.number = 12;

    }]);

Also see codepen: http://codepen.io/trueScript/pen/NqGzBM

When the page loads, the div element should have a class of '.quarter12', because of the corresponding variable values in the controller. However, instead, it throws an error. How do I get this to work?

ng-class expects expression not string you could fulfil your requirement using class with interpolation directive.

<div class="{{quarter+number}}">This shoul have a class of '.quarter12'</div>

Update

More better and convenient solution to set attribute value is by using ng-attr directive. ng-attr create and attribute with evaluated value of {{}} interpolation.

<div ng-attr-class="{{quarter+number}}">This shoul have a class of '.quarter12'</div>

Working Codepen

You could do something like this instead:

HTML:

<div ng-class="getClassName()">This should have a class of '.quarter12'</div>

JS:

angular.module('programApp.controllers', [])
    .controller('programController', ['$scope', '$filter', '$http', function($scope, $filter, $http){
         $scope.quarter = 'quarter';
         $scope.number = 12;

         $scope.getClassName = function() {
             retrun $scope.quarter + $scope.number;
         }
    }]);

http://codepen.io/anon/pen/PqPdmY

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM