计算对象数组的某些方面

时间:2014-09-27 11:14:53

标签: angularjs

我正在建立一个关于电视节目的网络应用,以学习AngularJS。部分内容是未见过的剧集。我想在标题栏中显示数字。然而,我从Laravel得到的是上周所有剧集的一系列对象。要使标题栏中的数字准确,我需要对其进行过滤。这是控制器的一部分:

$http.get('/episodes').success(function(data) {

    $scope.episodes = data; 

    console.log(data);

    $rootScope.numberForTitle = '(' + data.length + ')';

});

这就是它在控制台中记录的内容:

[Object, Object, Object, Object]
0: Object
    created_at: "2014-09-27 10:54:10"
    id: "8"
    name: "Boardwalk Empire"
    seen: "1"
    episode: "0503"
    userid: "1"
    __proto__: Object
1: Object
    created_at: "2014-09-27 10:49:41"
    id: "7"
    name: "Modern Family"
    seen: "0"
    episode: "0601"
    userid: "1"
    __proto__: Object
2: Object
    created_at: "0000-00-00 00:00:00"
    id: "6"
    name: "Sons of Anarchy"
    seen: "1"
    episode: "0701"
    userid: "1"
    __proto__: Object
3: Object
    created_at: "0000-00-00 00:00:00"
    id: "5"
    name: "The Big Bang Theory"
    seen: "0"
    episode: "0801"
    userid: "1"

如何按seen过滤此内容,或者至少让$rootScope.numberForTitle显示正确长度的看不见的节目?

2 个答案:

答案 0 :(得分:0)

只需循环播放所有剧集,只挑选看不见的剧集:

$scope.episodes = [];

for (var i = 0; i < data.length; i++) {
    if (data[i].seen != "1") {
        $scope.episodes.push(data[i]);
    }
}

$rootScope.numberForTitle = '(' + $scope.episodes.length + ')';

之后你没有说明你用它做什么(你是如何呈现它的),但是例如,可以在ng-repeat指令中添加一个过滤器。

答案 1 :(得分:0)

如果你想继续看到,那么将这些对象推送到另一个数组中:

//This will keep filtered data
$scope.unseen = []; 
$scope.episodes.forEach(function(elem) {
  if (elem.seen !== 1) {
    $scope.unseen.push(elem);
  }
});