親スコープを考えると、AngularJSですべての子スコープを入手する
-
11-12-2019 - |
質問
親スコープを考えると、すべての子スコープのリストを取得する方法を知りたいです。範囲の財産から見つけることができるのは$$育児、$$ Childtail、$$ NextSiblingと$$ prevsiblingです。
今すぐ使用しているアプローチは、親から育児を取得し、次のような子を使用して、次の子をNextSiblingがNULLに入れることです。
より良いアプローチはありますか? 私がすべての子供たちのメソッド[getModel]を呼びたいと考えると、これもまたこれをする方法はありますか?
解決
子指令は孤立したスコープを使用しており、そのようなものは親から見えない独自の値を持っています。親スコープからこれらの値にアクセスしたい。
「子スコープへのアクセスを必要とする親スコープ」の問題に対処する「角度」は、モデルを親に移動させ、子スコープを親のプロパティ/データ(子スコープではなく)を参照することです。自分のローカルプロパティ/コピーを持つ。たとえば、繰り返しが含まれている場合、つまり入力フォーム要素(つまり、各反復が双方向データバインディングが必要な場合)を含みます。
他のヒント
すべての角度範囲がDOM要素に接続されているため、現在の要素を使用して、到達したい子供を使用して子供を検査することから始めることができます。そこに一度下記の機能を使用して範囲を取得します。
angular.element('#5th_element').scope();
. AngularJS 1.3.2では、countChildScopes
法をNGMOCKモジュールに追加しました。
/** * @ngdoc method * @name $rootScope.Scope#$countChildScopes * @module ngMock * @description * Counts all the direct and indirect child scopes of the current scope. * * The current scope is excluded from the count. The count includes all isolate child scopes. * * @returns {number} Total number of child scopes. */ function countChildScopes(scope) { // jshint validthis: true var count = 0; // exclude the current scope var root = scope || angular.element(document).injector().get('$rootScope'); var pendingChildHeads = [root.$$childHead]; var currentScope; while (pendingChildHeads.length) { currentScope = pendingChildHeads.shift(); while (currentScope) { count += 1; pendingChildHeads.push(currentScope.$$childHead); currentScope = currentScope.$$nextSibling; } } return count; }.
IDを取得するための戻り値としてオブジェクトを使用します。
function enumerateChildScopes(scope) { // jshint validthis: true var enum = {}; // exclude the current scope var root = scope || angular.element(document).injector().get('$rootScope'); var pendingChildHeads = [root.$$childHead]; var currentScope; while (pendingChildHeads.length) { currentScope = pendingChildHeads.shift(); while (currentScope) { enum["scope"+pendingChildHeads.length] = currentScope.$id; pendingChildHeads.push(currentScope.$$childHead); currentScope = currentScope.$$nextSibling; } } return enum; }.
参考文献
-
Angularjs ChangeLog:1.3.2
所属していません StackOverflow