connectwithpalaniappan
connectwithpalaniappan

Reputation: 973

angularjs how to access ng-repeat filtered value outside its scope

I have a json defined in my scope like

   $scope.People = [  
    {  
          "firstName":"John",
          "lastName":"Doe",
          "Choices":[  
             {  
                "Name":"Dinner",
                "Options":[  
                   {  
                      "Name":"Fish",
                      "ID":1
                   },
                   {  
                      "Name":"Chicken",
                      "ID":2
                   },
                   {  
                      "Name":"Beef",
                      "ID":3
                   }
                ]
             },
             {  
                "Name":"Lunch",
                "Options":[  
                   {  
                      "Name":"Macaroni",
                      "ID":1
                   },
                   {  
                      "Name":"PB&J",
                      "ID":2
                   },
                   {  
                      "Name":"Fish",
                      "ID":3
                   }
                ]
             }
          ]
       },
       {  
          "firstName":"Jane",
          "lastName":"Doe"
       }
    ];

I have a search filter which search on the choices name and filter them. It is working fine. But I plan to display the number of results filtered (total results) outside all ng-repeat. Not sure how to get the scope of ng-repeat to its parent.

Code Snippet:

<div ng-controller="ExampleController">
  <input type="text" ng-model="q" placeholder="filter choices..." /><br/>
  <strong>Not Working :</strong>  I have {{results.length}} filtered results<br/><br/>
    <div ng-repeat="people in People" ng-hide="results.length == 0">
    <strong>Working :</strong>  I have {{results.length}} filtered results
    {{people.firstName}}
    <div ng-repeat="choice in results = (people.Choices | filter:q) ">
    {{ choice.Name }} 
    <select ng-model="choice.SelectedID"                 
           ng-options="option.Name for option in choice.Options"></select> {{choice.SelectedID}}
  </div>

Complete code @ http://plnkr.co/edit/ODW3lD?p=preview

Appreciate your response.

Upvotes: 2

Views: 2900

Answers (1)

glandrum101
glandrum101

Reputation: 466

The problem is that the ng-repeat creates a child scope and you are trying to reference the value in that child scope from a parent scope. In order to get around this, you should create a $scope.results = [] in your controller and then do:

<div ng-repeat="choice in $parent.results = (people.Choices | filter:q) ">

This will force it to store it in the results variable that is in the $parent scope ("ExampleController"), which is where you are trying to use it.

Here is a Plunker with it working:

http://plnkr.co/edit/pWua57wTffdX8dinPKRS?p=preview

Upvotes: 5

Related Questions