Julian
Julian

Reputation: 33

Get all the Scopes in an AngularJS aplication

I am wondering if there is a way to get all the Scopes in an AngularJS application, so I can manipulate all of them in the same level and organize them in a directive way or order?

Or if there is any way to get all the Scopes of the instances of a directive?

In case that this is not possible - could you explain why or provide me some ideas how would you approach this need?

Upvotes: 1

Views: 118

Answers (1)

Josh
Josh

Reputation: 44916

$scope objects are all linked lists under the hood. While it isn't necessarily recommended, you can use the private properties of scope to traverse that chain from the $rootScope, or whatever starting point you want down.

Below is a simple example of building out an <ul> with a directive to spit out each scope and associated $id into that list, preserving the hierarchy.

(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>

Upvotes: 1

Related Questions