我的范围内定义了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
感谢您的回复。
答案 0 :(得分:5)
问题是ng-repeat创建了一个子范围,并且您尝试从父范围引用该子范围中的值。为了解决这个问题,你应该在你的控制器中创建一个$ scope.results = [],然后执行:
<div ng-repeat="choice in $parent.results = (people.Choices | filter:q) ">
这会强制它将它存储在$ parent范围内的结果变量中(&#34; ExampleController&#34;),这是你尝试使用它的地方。
这是一个使用它的Plunker: