对象数组的角度过滤器

时间:2017-11-30 07:01:36

标签: angularjs angular-filters

在下面的代码中,console.log($scope.gradeC.title);显示正确的输出;但是下一个控制台行没有显示预期的输出。我不明白这种行为。任何建议/指示都会帮助我理解这一点。

<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
        <script>
            var myApp=angular.module("myApp", []);
            myApp.controller('myCtrl', function($scope, $filter)
            {

                console.log("Inside controller");

                  $scope.results = {
                    year:2013,
                    subjects:[
                      {title:'English',grade:'A'},
                      {title:'Maths',grade:'A'},
                      {title:'Science',grade:'B'},
                      {title:'Geography',grade:'C'}
                    ]
                  };                
                  console.log($scope.results);
                  $scope.gradeC = $filter('filter')($scope.results.subjects, {grade: 'B'})[0];
                    console.log($scope.gradeC.title);
                    console.log(($scope.results.subjects|{grade: 'B'})[0].title);
            }); 
        </script>
    </head>
    <body ng-app="myApp" ng-controller="myCtrl">
        <h4>Printing div</h4>
    </body>
</html>

1 个答案:

答案 0 :(得分:2)

您不能在控制器中使用|来过滤数组。

$scope.gradeC = $filter('filter')($scope.results.subjects, {grade: 'C'})[0];

console.log($scope.gradeC);

console.log($filter('filter')($scope.results.subjects, {grade: 'C'})[0].title);