2014-07-24 94 views
2

外部訪問NG重複濾波值我在我的範圍內定義的JSON像angularjs如何在其範圍

$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

像[這](http://plnkr.co/edit/uBG5y4WEQeEV7ryOS4zX?p=preview)? –

+0

不是。我希望在兩個重複之外。 – Pals

+0

爲什麼不在控制器中使用'$ filter'來過濾數據,然後再將它們寫入示波器?當您鍵入 – Kousha

回答

5

問題是ng-repeat創建一個子作用域,並且您試圖從父作用域引用該子作用域中的值。爲了解決這個問題,您應該創建一個$ scope.results = []在您的控制器,然後做:

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

這將迫使它存放在結果變量,在$父範圍(「ExampleController」),這是你試圖使用它的地方。

這裏正在與它Plunker:

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