gpt4 book ai didi

javascript - angularjs 如何访问其范围之外的 ng-repeat 过滤值

转载 作者:行者123 更新时间:2023-11-29 17:05:28 26 4
gpt4 key购买 nike

我在我的范围内定义了一个 json

   $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"
}
];

我有一个搜索过滤器,可以搜索选项名称并过滤它们。它工作正常。但我计划在所有 ng-repeat 之外显示过滤的结果数(总结果)。不确定如何将 ng-repeat 的范围获取到其父级。

代码片段:

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

完整代码@ http://plnkr.co/edit/ODW3lD?p=preview

感谢您的回复。

最佳答案

问题是 ng-repeat 创建了一个子作用域,而您正试图从父作用域引用该子作用域中的值。为了解决这个问题,您应该在 Controller 中创建一个 $scope.results = [] 然后执行:

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

这将强制它将它存储在 $parent 范围(“ExampleController”)中的结果变量中,这是您尝试使用它的地方。

这是一个可以正常工作的 Plunker:

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

关于javascript - angularjs 如何访问其范围之外的 ng-repeat 过滤值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24945582/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com