【问题标题】:angularjs how to access ng-repeat filtered value outside its scopeangularjs如何在其范围之外访问ng-repeat过滤值
【发布时间】:2014-07-24 23:20:45
【问题描述】:

我在我的范围内定义了一个 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

感谢您的回复。

【问题讨论】:

  • 类似this?
  • 不。我希望它在两个 ng-repeat 之外。
  • 为什么不在控制器内部使用$filter 在将数据写入作用域之前对其进行过滤?并且您可以在键入时绑定一个关键事件以重新过滤
  • 能否提供示例代码。我会试试看。

标签: javascript angularjs angularjs-ng-repeat


【解决方案1】:

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

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

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

这是一个正在运行的 Plunker:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 2023-03-13
    • 2014-02-06
    • 2016-06-06
    相关资源
    最近更新 更多