Reputation: 766
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?
Upvotes: 2
Views: 132
Reputation: 3986
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
Upvotes: 1
Reputation: 136184
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>
Upvotes: 4