angularjs
Improve this Doc View Source $rootScope.Scope
- type in module ng
A root scope can be retrieved using the $rootScope key from the $injector. Child scopes are created using the $new() method. (Most scopes are created automatically when compiled HTML template is executed.) See also the Scopes guide for an in-depth introduction and usage examples.
Inheritance
A scope can inherit from a parent scope, as in this example:
var parent = $rootScope; var child = parent.$new(); parent.salutation = "Hello"; expect(child.salutation).toEqual('Hello'); child.salutation = "Welcome"; expect(child.salutation).toEqual('Welcome'); expect(parent.salutation).toEqual('Hello');
When interacting with Scope
in tests, additional helper methods are available on the instances of Scope
type. See ngMock Scope for additional details.
Usage
$rootScope.Scope([providers], [instanceCache]);
Arguments
Param | Type | Details |
---|---|---|
providers (optional) | Object.<string, function()>= | Map of service factory which need to be provided for the current scope. Defaults to |
instanceCache (optional) | Object.<string, *>= | Provides pre-instantiated services which should append/override services provided by |
Returns
Object |
Newly created scope. |
Methods
-
$new(isolate, parent);
Creates a new child scope.
The parent scope will propagate the $digest() event. The scope can be removed from the scope hierarchy using $destroy().
$destroy() must be called on a scope when it is desired for the scope and its child scopes to be permanently detached from the parent and thus stop participating in model change detection and listener notification by invoking.
Parameters
Param Type Details isolate boolean
If true, then the scope does not prototypically inherit from the parent scope. The scope is isolated, as it can not see parent scope properties. When creating widgets, it is useful for the widget to not accidentally read parent state.
parent (optional)Scope
The
Scope
that will be the$parent
of the newly created scope. Defaults tothis
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.(default: this)
Returns
Object
The newly created child scope.
-
$watch(watchExpression, listener, [objectEquality]);
Registers a
listener
callback to be executed whenever thewatchExpression
changes.- The
watchExpression
is called on every call to $digest() and should return the value that will be watched. (watchExpression
should not change its value when executed multiple times with the same input because it may be executed multiple times by $digest(). That is,watchExpression
should be idempotent. - The
listener
is called only when the value from the currentwatchExpression
and the previous call towatchExpression
are not equal (with the exception of the initial run, see below). Inequality is determined according to reference inequality, strict comparison via the!==
Javascript operator, unlessobjectEquality == true
(see next point) - When
objectEquality == true
, inequality of thewatchExpression
is determined according to theangular.equals
function. To save the value of the object for later comparison, theangular.copy
function is used. This therefore means that watching complex objects will have adverse memory and performance implications. - The watch
listener
may change the model, which may trigger otherlistener
s to fire. This is achieved by rerunning the watchers until no changes are detected. The rerun iteration limit is 10 to prevent an infinite loop deadlock.
If you want to be notified whenever $digest is called, you can register a
watchExpression
function with nolistener
. (Be prepared for multiple calls to yourwatchExpression
because it will execute multiple times in a single $digest cycle if a change is detected.)After a watcher is registered with the scope, the
listener
fn is called asynchronously (via $evalAsync) to initialize the watcher. In rare cases, this is undesirable because the listener is called when the result ofwatchExpression
didn't change. To detect this scenario within thelistener
fn, you can compare thenewVal
andoldVal
. If these two values are identical (===
) then the listener was called due to initialization.// let's assume that scope was dependency injected as the $rootScope var scope = $rootScope; scope.name = 'misko'; scope.counter = 0; expect(scope.counter).toEqual(0); scope.$watch('name', function(newValue, oldValue) { scope.counter = scope.counter + 1; }); expect(scope.counter).toEqual(0); scope.$digest(); // the listener is always called during the first $digest loop after it was registered expect(scope.counter).toEqual(1); scope.$digest(); // but now it will not be called unless the value changes expect(scope.counter).toEqual(1); scope.name = 'adam'; scope.$digest(); expect(scope.counter).toEqual(2); // Using a function as a watchExpression var food; scope.foodCounter = 0; expect(scope.foodCounter).toEqual(0); scope.$watch( // This function returns the value being watched. It is called for each turn of the $digest loop function() { return food; }, // This is the change listener, called when the value returned from the above function changes function(newValue, oldValue) { if ( newValue !== oldValue ) { // Only increment the counter if the value changed scope.foodCounter = scope.foodCounter + 1; } } ); // No digest has been run so the counter will be zero expect(scope.foodCounter).toEqual(0); // Run the digest but since food has not changed count will still be zero scope.$digest(); expect(scope.foodCounter).toEqual(0); // Update food and run digest. Now the counter will increment food = 'cheeseburger'; scope.$digest(); expect(scope.foodCounter).toEqual(1);
Parameters
Param Type Details watchExpression function()
string
Expression that is evaluated on each $digest cycle. A change in the return value triggers a call to the
listener
.-
string
: Evaluated as expression -
function(scope)
: called with currentscope
as a parameter.
listener function(newVal, oldVal, scope)
Callback called whenever the value of
watchExpression
changes.-
newVal
contains the current value of thewatchExpression
-
oldVal
contains the previous value of thewatchExpression
-
scope
refers to the current scope
objectEquality (optional)boolean
Compare for object equality using
angular.equals
instead of comparing for reference equality.Returns
function()
Returns a deregistration function for this listener.
- The
-
$watchGroup(watchExpressions, listener);
A variant of $watch() where it watches an array of
watchExpressions
. If any one expression in the collection changes thelistener
is executed.- The items in the
watchExpressions
array are observed via standard $watch operation and are examined on every call to $digest() to see if any items changes. - The
listener
is called whenever any expression in thewatchExpressions
array changes.
Parameters
Param Type Details watchExpressions Array.<string|Function(scope)>
Array of expressions that will be individually watched using $watch()
listener function(newValues, oldValues, scope)
Callback called whenever the return value of any expression in
watchExpressions
changes ThenewValues
array contains the current values of thewatchExpressions
, with the indexes matching those ofwatchExpression
and theoldValues
array contains the previous values of thewatchExpressions
, with the indexes matching those ofwatchExpression
Thescope
refers to the current scope.Returns
function()
Returns a de-registration function for all listeners.
- The items in the
-
$watchCollection(obj, listener);
Shallow watches the properties of an object and fires whenever any of the properties change (for arrays, this implies watching the array items; for object maps, this implies watching the properties). If a change is detected, the
listener
callback is fired.- The
obj
collection is observed via standard $watch operation and is examined on every call to $digest() to see if any items have been added, removed, or moved. - The
listener
is called whenever anything within theobj
has changed. Examples include adding, removing, and moving items belonging to an object or array.
$scope.names = ['igor', 'matias', 'misko', 'james']; $scope.dataCount = 4; $scope.$watchCollection('names', function(newNames, oldNames) { $scope.dataCount = newNames.length; }); expect($scope.dataCount).toEqual(4); $scope.$digest(); //still at 4 ... no changes expect($scope.dataCount).toEqual(4); $scope.names.pop(); $scope.$digest(); //now there's been a change expect($scope.dataCount).toEqual(3);
Parameters
Param Type Details obj string
function(scope)
Evaluated as expression. The expression value should evaluate
- The