2017-11-30 17 views
-1

아래 코드에서 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> 
+0

유 주제 속성에 필터를 호출 하시겠습니까? –

+0

"* 올바른 출력을 보여줍니다 *"- 어느 것입니까? – Rafalon

+0

올바른 출력은 C 등급의 지리입니다. –

답변

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); 
+0

감사합니다. 필터 배열에서 키와 값을 큰 따옴표로 묶을 필요가 없습니까? –

+0

이 경우 C가 문자열 값인 문자열'{grade : 'C'} '이면 값을 따옴표로 묶습니다. –

+0

감사합니다. 내 결과가 다음과 같은 경우 : \t \t \t \t $ scope.results = [{ "name": "John", "age": "30", "city": "New York"}, { "name" : "John1", "age": "31", "city": "New York"}, { "name": "John2", "age": "32", "city": "New York"}, { "name": "John3", "age": "", "city": "New York"},]; 코드 console.log ($ filter ('filter') ($ scope.results, {age : ''}) [0] .name);가 필요합니다. John3을 반환합니다. 그러나 그것은 John을 돌려줍니다. $ filter ('filter') ($ scope.results, {age : ''}가 전체 배열을 반환하는 이유를 알려주십시오. 미리 감사드립니다. –