2014-10-20 18 views
1

我想知道是否有辦法在AngularJS應用程序中獲取所有範圍,因此我可以在同一級別操作它們中的所有範圍並以指令方式或順序組織它們?在AngularJS應用程序中獲取所有範圍

或者如果有任何方法可以獲得指令實例的所有範圍?

萬一這不可能 - 你能解釋一下爲什麼或者給我一些想法,你會如何處理這種需求?

+0

你可以用'$ rootScope'有來自所有範圍全局訪問...或者你可以寫通過檢查'$穿越了'$ scope'鏈的方法父母' – tymeJV 2014-10-20 16:28:24

+0

您應該永遠不需要在組織良好的應用程序中執行此操作。你試圖用這個來達到什麼目的? – Blazemonger 2014-10-20 16:51:25

+0

您可以使用您可以在index.html頂部定義的主控制器。 將該範圍定義爲對象,並且您可以在整個應用程序中使用相同的範圍變量 – 2014-10-20 16:53:52

回答

1

$scope objects都是引擎蓋下的鏈表。雖然不一定建議,但您可以使用範圍的私有屬性遍歷$rootScope的鏈,或者您想要的任何起始點。

下面是一個簡單的例子,用<ul>構建一個指令,將每個範圍和相關的$id吐出到該列表中,以保留層次結構。

(function() { 
 

 
    function ShowScope($rootScope) { 
 

 
    function renderScope(scope, elem, level) { 
 
     var level = (level || 1); 
 
     var li = angular.element('<li>'); 
 
     var p = angular.element('<p>'); 
 
     p.text(scope.$id); 
 

 
     li.addClass('level-' + level); 
 
     li.append(p); 
 

 
     if (scope.$$childHead) { 
 

 
     var ul = angular.element('<ul>'); 
 
     
 
     renderScope(scope.$$childHead, ul, level + 1); 
 
     
 
     li.append(ul); 
 
     } 
 
     
 
     if(scope.$$nextSibling){ 
 
     renderScope(scope.$$nextSibling, elem, level); 
 
     } 
 

 
     elem.append(li); 
 
    } 
 

 
    return { 
 
     restrict: 'E', 
 
     link: function(scope, elem, attrs) { 
 
     scope.$watch(function() { 
 

 
      elem.empty(); 
 

 
      var ul = angular.element('<ul>'); 
 
      ul.addClass('list-unstyled'); 
 
      renderScope($rootScope, ul); 
 
      elem.append(ul); 
 
     }); 
 
     } 
 
    }; 
 
    } 
 
    ShowScope.$inject = ['$rootScope']; 
 

 
    angular.module('scope-app', []) 
 
    .directive('showScope', ShowScope); 
 

 
}());
.level-1{ 
 
    background-color:rgb(255, 0, 0); 
 
} 
 

 
.level-2{ 
 
    background-color:rgb(200, 0, 0); 
 
} 
 

 
.level-3{ 
 
    background-color:rgb(150, 0, 0); 
 
}
<script src="http://code.angularjs.org/1.3.0/angular.js"></script> 
 
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" /> 
 

 
<!-- --> 
 
<div class="container" ng-app="scope-app" ng-init="nums=[1,2,3,4,5]"> 
 
    <div class="row"> 
 
    <div class="col-sm-12"> 
 
     <show-scope></show-scope> 
 
    </div> 
 
    </div> 
 
    <div class="row"> 
 
    <div class="col-sm-12"> 
 
     <div ng-repeat="n1 in nums"> 
 
     <p ng-repeat="n2 in nums"> 
 
     {{n1}}:{{n2}} 
 
     </p> 
 
     </div> 
 
    </div> 
 
    </div> 
 
</div>

相關問題