2014-06-26 38 views
1

什麼是解決以下問題的正確方式:如何設置一個匿名子範圍,設置角

我有這樣的事情:

<div ng-click="!showAll">Show All</div> 
<div ng-repeat="foo in foos"> 
    <div ng-click="!showSubItems">Do Stuff</div> 
    <div ng-show="showSubItems"> 
     <div ng-repeat="bar in foo.bars"> 
      <div>{{bar.stuff}}</div> 
     </div> 
    </div> 
</div> 

而且我想展示的所有經歷每個欄項目並通過更改showSubItems來擴展它。我已經搜索了一遍,我發現的唯一答案是當子範圍有一個控制器時處理。在我的情況下,我沒有明確的控制器,因爲它們非常基本。有沒有辦法告訴每個應該設置showSubItems = true的子作用域?

我試過<div ng-show="showSubItems||showAll">,但是我打不開摺疊兒童物品。我可以在foo模型上添加一些東西,但是這似乎是不正確的處理方法,因爲當模型沒有任何關於UI的知識或關注時,它將數據添加到模型中。

回答

1

我能想到的不使用控制器的唯一方法是使用$$ childHead遍歷子範圍並將showSubItems設置爲true。雖然這有效,但訪問$$ childHead並不是真的「正確」,因爲它應該被認爲是AngularJS的私有。這裏的SHOWALL的樣子:

$scope.showAll = function() { 
    var childScope = $scope.$$childHead; 
    while (childScope) { 
     childScope.showSubItems = true; 
     childScope = childScope.$$nextSibling; 
    } 
}; 

例子:在我看來http://jsfiddle.net/JFcKs/

更正確的解決辦法是給每個foo的控制器監聽到由父廣播的「SHOWALL」事件當全部點擊時的範圍。

例子:http://jsfiddle.net/v586a/

1

試試這個...我沒有你的收藏品不看怎麼樣。所以我編了簡單的字符串數組。

<div ng-controller="MyTestController"> 
<div ng-click="showAll = !showAll" ng-init="showAll=false">Show All</div> 
<div ng-repeat="foo in foos"> 
    <div ng-click="showSubItems = !showSubItems" ng-init="showSubItems=false">Do Stuff</div> 
    <div ng-show="showSubItems || showAll"> 
     <div ng-repeat="bar in bars"> 
      <div>{{bar}}</div> 
     </div> 
    </div> 
</div> 

<script type="text/javascript"> 
    WebPortal.controller('MyTestController', ['$scope',function ($scope) { 
     $scope.foos = ['Foo1', 'Foo2', 'Foo3']; 
     $scope.bars = ['Bar1', 'Bar2', 'Bar3']; 
    }]); 
</script> 
+0

對不起忘了把原代碼,酒吧是FOO的孩子。我試過||聲明,但是它們總是顯示出來,直到再次單擊按鈕後才能關閉。 – Zipper