我试图根据控制器返回的值设置图标样式,控制台日志显示正确触发的值但似乎我有一个Ng类表达式的问题。对此有任何帮助非常感谢。提前致谢 。
控制器代码
$scope.class = "favorite_border";
$scope.changeClass = function(){
if ($scope.class === "favorite_border")
$scope.class = "favorite";
else
$scope.class = "favorite_border";
console.log($scope.class);
}
查看代码
<i ion-ripple ion-ripple-color="#ff0000"class="material-icons" style="font-size: 32px" ng-click="changeClass()" ng-class="'{{class}}'== favorite_border ? 'favorite_border' : 'favorite'"> {{class}}</i>
CSS样式
.favorite_border{ color:gray};.favorite{color:red};
答案 0 :(得分:2)
设置您的视图:
<i ion-ripple ion-ripple-color="#ff0000"class="material-icons" style="font-size: 32px" ng-click="changeClass()" ng-class="class === 'favorite_border' ? 'favorite_border' : 'favorite'"> {{class}}</i>
或基于上面的控制器代码:
<i ion-ripple ion-ripple-color="#ff0000"class="material-icons" style="font-size: 32px" ng-click="changeClass()" ng-class="class"> {{class}}</i>
答案 1 :(得分:1)
只需将其更改为
即可ng-class="class == 'favorite_border' ? 'favorite_border' : 'favorite'"
甚至
ng-class="class"
请记住使用您想要的适当初始类初始化$scope.class='...'
。
<强> Exaplanation:强>
ng-class
中的表达式将被评估为JS中的或多或少的表达式 - 变量以$scope
为前缀。因此,如果我们看一下你的表达:
'{{class}}'== favorite_border ? 'favorite_border' : 'favorite'
它将被解释为:
'{{$scope.class}}'== $scope.favorite_border ? 'favorite_border' : 'favorite'
反过来将推断为:
''== $scope.favorite_border ? 'favorite_border' : 'favorite'
最初,直到你切换课程,
'favorite_border'== $scope.favorite_border ? 'favorite_border' : 'favorite'
它们在上下文中都没有意义(第一个和第二个将是false ? 'favorite_border' : 'favorite'
==&gt; 'favorite'
)并且不会评估为预期的类名。
答案 2 :(得分:1)
在评估条件时不要使用表达式,将其更改为
<i ion-ripple ion-ripple-color="#ff0000"class="material-icons" style="font-size: 32px" ng-click="changeClass()" ng-class="class === 'favorite_border' ? 'favorite_border' : 'favorite'"> {{class}}</i>
<强>样本强>
.favorite_border{ color:yellow};.favorite{color:red};
&#13;
<html>
<head>
<body>
<div ng-app="app" ng-controller="ctrl">
<i ion-ripple ion-ripple-color="#ff0000"class="material-icons" style="font-size: 32px" ng-click="changeClass()" ng-class="class == 'favorite_border' ? 'favorite_border' : 'favorite'"> {{class}}</i>
</div>
<!-- Angular Material Dependencies -->
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.6/angular.js"></script>
<script>
var app = angular.module('app', []);
app.controller("ctrl", function($scope) {
$scope.class = "favorite_border";
$scope.changeClass = function(){
if ($scope.class === "favorite_border")
$scope.class = "favorite";
else
$scope.class = "favorite_border";
console.log($scope.class);
}
});
</script>
</body>
</html>
&#13;