feat(Scope): allow the parent of a new scope to be specified on creation

This enables us to place transclude scopes more accurately in the scope hierarchy.
This commit is contained in:
Peter Bacon Darwin
2014-09-25 21:06:07 +01:00
parent 07e3abc7dd
commit 6417a3e9eb
2 changed files with 24 additions and 7 deletions

View File

@@ -184,12 +184,20 @@ function $RootScopeProvider(){
* When creating widgets, it is useful for the widget to not accidentally read parent
* state.
*
* @param {Scope} [parent=this] The {@link ng.$rootScope.Scope `Scope`} that will be the `$parent`
* of the newly created scope. Defaults to `this` scope if not provided.
* This is used when creating a transclude scope to correctly place it
* in the scope hierarchy while maintaining the correct prototypical
* inheritance.
*
* @returns {Object} The newly created child scope.
*
*/
$new: function(isolate) {
$new: function(isolate, parent) {
var child;
parent = parent || this;
if (isolate) {
child = new Scope();
child.$root = this.$root;
@@ -213,13 +221,13 @@ function $RootScopeProvider(){
child = new this.$$ChildScope();
}
child['this'] = child;
child.$parent = this;
child.$$prevSibling = this.$$childTail;
if (this.$$childHead) {
this.$$childTail.$$nextSibling = child;
this.$$childTail = child;
child.$parent = parent;
child.$$prevSibling = parent.$$childTail;
if (parent.$$childHead) {
parent.$$childTail.$$nextSibling = child;
parent.$$childTail = child;
} else {
this.$$childHead = this.$$childTail = child;
parent.$$childHead = parent.$$childTail = child;
}
return child;
},

View File

@@ -72,6 +72,15 @@ describe('Scope', function() {
expect(child.$new).toBe($rootScope.$new);
expect(child.$root).toBe($rootScope);
}));
it("should attach the child scope to a specified parent", inject(function($rootScope) {
var isolated = $rootScope.$new(true);
var trans = $rootScope.$new(false, isolated);
$rootScope.a = 123;
expect(isolated.a).toBeUndefined();
expect(trans.a).toEqual(123);
expect(trans.$parent).toBe(isolated);
}));
});