[英]Angular ngClass Not Evaluating to Class Names
我正在嘗試使用ng-class創建自定義類名稱。 我想結合兩個范圍變量的值來創建該名稱。 這是我的代碼:
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;
}]);
另請參閱codepen: http ://codepen.io/trueScript/pen/NqGzBM
頁面加載時,由於控制器中的相應變量值,div元素應具有“ .quarter12”類。 但是,相反,它將引發錯誤。 我該如何工作?
ng-class
期望expression
不是string
您可以使用帶內插指令的類來滿足您的要求。
<div class="{{quarter+number}}">This shoul have a class of '.quarter12'</div>
更新
使用ng-attr
指令可以更好,更方便地設置屬性值。 ng-attr
創建並賦值為{{}}
插值的屬性。
<div ng-attr-class="{{quarter+number}}">This shoul have a class of '.quarter12'</div>
您可以改為執行以下操作:
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;
}
}]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.