2015-11-02 49 views
0

我在計算如何在對象數組上使用具有特定屬性的ng-if指令時遇到了一些麻煩。對包含對象的數組顯示ng-

陣:

[{"Id":1087, 
"CreateDate":"2015-11-02T19:26:39.007", 
"Message":"Some text in here...", 
"AffectedDate":null, 
"Type":"a", 
"CreatePeriod":"Today", 
"CreateDateString":"Monday, November 2, 2015 7:26 PM"}, 
{"Id":1086, 
"CreateDate":"2015-11-02T19:26:25.2", 
"Message":"Some text in here...", 
"AffectedDate":null, 
"Type":"a", 
"CreatePeriod":"Yesterday", 
"CreateDateString":"Monday, November 2, 2015 7:26 PM"}, 
{"Id":1085, 
"CreateDate":"2015-11-02T19:26:13.677", 
"Message":"Some text in here...", 
"AffectedDate":"2015-10-30T07:00:00", 
"Type":"a", 
"CreatePeriod":"Older", 
"CreateDateString":"Monday, November 2, 2015 7:26 PM"}] 

以上是下來對象的數組,我想在下面的標題使用NG秀指令。

<h3 ng-show="">Last Week</h3> 

我想和NG-一個使用該物業是CreatePeriod

使用上面的HTML,因爲不存在與有CreatePeriod「上週」我希望隱藏標題沒有對象。

這可以通過簡單的ng顯示來實現嗎?或者是否需要將ng-repeat與ng-show結合使用?

謝謝!

+1

所以,你會喜歡的標題是存在,如果陣列中的至少一個元件具有''CreatePeriod「:」上週「',是嗎? –

+1

http://stackoverflow.com/questions/31944037/how-to-use-ng-show-when-a-key-with-a-certain-value-exists-in-an-array –

+0

謝謝Matt,didn'在搜索時看不到這個帖子。它使我相信ng-repeat是必要的,但這是真的嗎? – Flignats

回答

1

您可以創建在控制器的方法來檢查你的病情:

$scope.data = [{ 
    "Id": 1087, 
    "CreateDate": "2015-11-02T19:26:39.007", 
    "Message": "Some text in here...", 
    "AffectedDate": null, 
    "Type": "a", 
    "CreatePeriod": "Today", 
    "CreateDateString": "Monday, November 2, 2015 7:26 PM" 
}, { 
    "Id": 1086, 
    "CreateDate": "2015-11-02T19:26:25.2", 
    "Message": "Some text in here...", 
    "AffectedDate": null, 
    "Type": "a", 
    "CreatePeriod": "Yesterday", 
    "CreateDateString": "Monday, November 2, 2015 7:26 PM" 
}, { 
    "Id": 1085, 
    "CreateDate": "2015-11-02T19:26:13.677", 
    "Message": "Some text in here...", 
    "AffectedDate": "2015-10-30T07:00:00", 
    "Type": "a", 
    "CreatePeriod": "Older", 
    "CreateDateString": "Monday, November 2, 2015 7:26 PM" 
}]; 

$scope.checkCreatePeriod = function(value) { 

    var result = false; 
    angular.forEach($scope.data, function(obj) { 

     if (obj['CreatePeriod'] === value && result === false) { 
      result = true; 
     } 

    }); 

    return result; 
} 

在View:

<h3 ng-show="checkCreatePeriod('LastWeek')">Last Week</h3> 
+0

感謝您的建議。我猜測使用ng-repeat或控制器邏輯將是唯一的方法。我選擇了這種方法,因爲通過控制器進行過濾似乎更合適。 – Flignats