当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - 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.

网友答案:

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

分享给朋友:
您可能感兴趣的文章:
随机阅读: