Angularjs如何访问ng-repeat作用域外的过滤值

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

本文关键字:作用域 过滤 ng-repeat 何访问 访问 Angularjs      更新时间:2023-09-26

我有一个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创建了一个子作用域,而您试图从父作用域引用该子作用域中的值。为了解决这个问题,您应该创建一个$scope。结果=[]在你的控制器,然后做:

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

这将强制将它存储在$parent作用域("ExampleController")中的结果变量中,这就是您试图使用它的地方。

这是一个活塞与它的工作:

http://plnkr.co/edit/pWua57wTffdX8dinPKRS?p =预览