2016-02-02 35 views
0

可以將ng樣式和返回非布爾值的函數一起使用嗎?在開關語句中使用ng樣式 - angular js

我想根據我的模型和 一個屬性顏色不同BG我沒做到這一點

<tr ng-repeat="issue in data.issues|orderBy:orderByField:reverseSort" ng-style="{'background-color': isToday(issue.due_date) ? 'red': 'yellow'}" > 
    ... 

控制器:

$scope.isToday = function (compareDate) { 
     var today = $scope.today; 
     return compareDate < today.getFullYear() + '-' + today.getDate() + '-' + today.getMonth(); 
    } 

其中isToday函數返回一個布爾值。

如何處理我的函數返回3個值(或更多)的情況,並根據其結果想要3種不同的背景顏色?

+0

你正在做一個基於文本的日期對象的比較....這將不會像'2016-31-01'會正確的將大於'2016-2-1' –

+0

謝謝阿倫,但組成該功能不是我的問題。我想知道是否可以將ngStyle與可以返回3個不同值並且不是2的函數結合使用(作爲布爾值) – eeadev

+0

實現一個函數,該函數根據日期獲取日期並返回唯一的rgb顏色,並使用它作爲'background-color'的值。 – URL87

回答

2

使用ngClass。 模板:

<tr ng-repeat="issue in data.issues|orderBy:orderByField:reverseSort" ng-class="{{ myClass }}" > 

CSS:

.one { 
    background-color: red; 
} 

.two { 
    background-color: blue; 
} 

.three { 
    background-color: green; 
} 

JS:

$scope.myClass = 'three' // or 'one', or 'two' 
+0

那是什麼?你如何通過issue.due_date? – eeadev

+1

例如:https://jsfiddle.net/gtug5ej2/2/請參閱文檔 - https://docs.angularjs.org/api/ng/directive/ngClass –

0

我剛纔想給你concept-如何可以達到你想要什麼,請更新根據someFun功能給你需要即date

下面的例子試圖根據條件評估來放置不同的類。如果你需要一些修改,請讓我知道我會做正確的方式。

angular.module('app', []) 
 
    .controller('ctrl', function ($scope) { 
 
     
 
    //sample items 
 
    $scope.items = ['One', 
 
        'Two', 
 
        'Three', 
 
        'Four', 
 
        'Five', 
 
        'Six', 
 
        'Seven', 
 
        'Eight', 
 
        'Nine']; 
 
    //this is function where multiple condtions will be handled 
 
    $scope.someFunc = function(index, cond){ 
 
    //some sample conditions, write here according to your requirements 
 
    if(index >6 && index%22 && cond == 'c') 
 
    return true; 
 
    if(index%2 && cond == 'a') 
 
    return true; 
 
    if(index%3 && cond == 'b') 
 
    return true; 
 
    else return false; 
 
    } 
 
    
 
});
.green{ 
 
    background-color:green; 
 
    border: 1px solid white; 
 
    color:white; 
 
} 
 
.blue{ 
 
    background-color:blue; 
 
    border: 1px solid white; 
 
} 
 
.red{ 
 
    background-color:red; 
 
    border: 1px solid white; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 

 
<div ng-app="app" ng-controller="ctrl"> 
 
    <div ng-repeat="item in items" ng-class="{ 'blue': someFunc($index, 'a'), 'green': someFunc($index, 'b'), 'red': someFunc($index, 'c') }"> {{item}} 
 
    </div> 
 
</div>

快樂幫助!