我在我的范围内定义了一个 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:
关于javascript - angularjs如何访问其范围之外的ng-repeat过滤值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24945582/