根据 AngularJS 中的条件应用文本以悬停



如何使用 angularjs 根据逻辑选择要在悬停中显示的特定文本? 例如,我有一个值,如果类等于"警告",我想要特定的悬停消息,如果类等于"成功",我希望出现不同的悬停消息。

我的逻辑是编写一个函数,说明如果颜色=成功悬停=这个,如果颜色=警告悬停=那个,如果颜色=错误悬停=其他东西。 有什么建议吗?

getColor = function() {
var data = 88;
if(data < 75){
return "losses-success";
}else
if(data >=75 && data < 90){
return "losses-warning";
}else
if(data > 90){
return "losses-error";
}
};
.losses-success{
display: inline-block!important;
width: 8px;
height: 20px;
background-color: green;
}
.losses-warning{
display: inline-block!important;
width: 8px;
height: 20px;
background-color: yellow;
}
.losses-error{
display: inline-block!important;
width: 8px;
height: 20px;
background-color: red;
}
<div id="cTotal" class="losses-tooltip" ng-class="getColor()">
<span class="tooltiptext"> </span>
<span class="block"><sup>$</sup>
<strong class="amount">{{loss}}</strong></span>
</div>

如果你的类和消息是固定的,我认为最好返回一个带有类和消息的对象:

return {
ngclass: "losses-success",
message: "some text"
}

您可以在 ng-class 中使用 class 属性并显示与该属性相关的消息。

<div id="cTotal" class="losses-tooltip" ng-class="getColor().ngclass">
{{getColor().message}}
</div>

我不太喜欢这种方法,因为 getColor(( 函数在每个角度循环中都会被调用。getColor((.ngclass 语法对我来说似乎很奇怪。

我更喜欢在控制器中设置对象,并在需要时更新值。如果无法控制何时更新类和消息,则可以选择第一种方法。如果您能够控制这一点,您可以简单地:

function getColor(value) {
//put you logic
//
$scope.myObj = {
ngclass: "anyclass",
message: "any message"
}
}

在您的模板中:

<div id="cTotal" class="losses-tooltip" ng-class="myObj.ngclass">
{{myObj.message}}
</div>

请注意,在第二种方法中,您需要调用 getColor 函数来更新 myObj 中的值,以便获得更好的性能。

在第一种方法中,函数在每个周期调用,因此每次都会更新值(无需在控制器中显式调用函数即可更新值(。因此,在这种情况下,您需要注意应用程序的性能。

我真的不写Angular.js...所以这不是最好的方法 - 我敢肯定...但它更像是一个你应该如何创建一个JSFIDDLE的例子 - 并在问之前更多地解决问题:http://jsfiddle.net/sheriffderek/U3pVM/33739/

应用设置(+控制器(

var app = angular.module('ExampleApp', [/* no dependencies */]);
app.controller('ExampleCtrl', function($scope) {
$scope.crapList = [57, 94, 72, 20];
$scope.getColor = function(inputData) {
if (inputData > 90) {
return 'error';
}
if (inputData > 70) {
return 'warning';
}
return 'success';
};
});

模板

<main ng-app="ExampleApp">
<h1>Example</h1>
<section ng-controller="ExampleCtrl">
<ul class="crap-list">
<li class="crap" ng-class='getColor(crap)'
ng-repeat="crap in crapList">
<span>{{crap}}</span>
</li>
</ul>
</section>
</main>

风格

.crap {
/* display: inline-block!important; 
if you have to add !important... then you are doing something very wrong further up your style-sheet*/
/* width: 8px;  what? this is a bad idea */
/* height: 20px;  the content should determine it's height */
margin-top: .2rem;
padding: .5rem;
display: inline-block;
margin: 2px;
}
.crap.success {
background: green;
}
.crap.warning {
background: orange;
}
.crap.error {
background: red;
}

最新更新