目录搜索
AngularJS API Referenceautoauto/serviceauto/service/$injectorauto/service/$providengng/directiveng/directive/ang/directive/formng/directive/inputng/directive/input[checkbox]ng/directive/input[date]ng/directive/input[dateTimeLocal]ng/directive/input[email]ng/directive/input[month]ng/directive/input[number]ng/directive/input[radio]ng/directive/input[text]ng/directive/input[time]ng/directive/input[url]ng/directive/input[week]ng/directive/ngAppng/directive/ngBindng/directive/ngBindHtmlng/directive/ngBindTemplateng/directive/ngBlurng/directive/ngChangeng/directive/ngCheckedng/directive/ngClassng/directive/ngClassEvenng/directive/ngClassOddng/directive/ngClickng/directive/ngCloakng/directive/ngControllerng/directive/ngCopyng/directive/ngCspng/directive/ngCutng/directive/ngDblclickng/directive/ngDisabledng/directive/ngFocusng/directive/ngFormng/directive/ngHideng/directive/ngHrefng/directive/ngIfng/directive/ngIncludeng/directive/ngInitng/directive/ngKeydownng/directive/ngKeypressng/directive/ngKeyupng/directive/ngListng/directive/ngModelng/directive/ngModelOptionsng/directive/ngMousedownng/directive/ngMouseenterng/directive/ngMouseleaveng/directive/ngMousemoveng/directive/ngMouseoverng/directive/ngMouseupng/directive/ngNonBindableng/directive/ngOpenng/directive/ngPasteng/directive/ngPluralizeng/directive/ngReadonlyng/directive/ngRepeatng/directive/ngSelectedng/directive/ngShowng/directive/ngSrcng/directive/ngSrcsetng/directive/ngStyleng/directive/ngSubmitng/directive/ngSwitchng/directive/ngTranscludeng/directive/ngValueng/directive/scriptng/directive/selectng/directive/textareang/filterng/filter/currencyng/filter/dateng/filter/filterng/filter/jsonng/filter/limitTong/filter/lowercaseng/filter/numberng/filter/orderByng/filter/uppercaseng/functionng/function/angular.bindng/function/angular.bootstrapng/function/angular.copyng/function/angular.elementng/function/angular.equalsng/function/angular.extendng/function/angular.forEachng/function/angular.fromJsonng/function/angular.identityng/function/angular.injectorng/function/angular.isArrayng/function/angular.isDateng/function/angular.isDefinedng/function/angular.isElementng/function/angular.isFunctionng/function/angular.isNumberng/function/angular.isObjectng/function/angular.isStringng/function/angular.isUndefinedng/function/angular.lowercaseng/function/angular.moduleng/function/angular.noopng/function/angular.toJsonng/function/angular.uppercaseng/objectng/object/angular.versionng/providerng/provider/$animateProviderng/provider/$compileProviderng/provider/$controllerProviderng/provider/$filterProviderng/provider/$httpProviderng/provider/$interpolateProviderng/provider/$locationProviderng/provider/$logProviderng/provider/$parseProviderng/provider/$rootScopeProviderng/provider/$sceDelegateProviderng/provider/$sceProviderng/serviceng/service/$anchorScrollng/service/$animateng/service/$cacheFactoryng/service/$compileng/service/$controllerng/service/$documentng/service/$exceptionHandlerng/service/$filterng/service/$httpng/service/$httpBackendng/service/$interpolateng/service/$intervalng/service/$localeng/service/$locationng/service/$logng/service/$parseng/service/$qng/service/$rootElementng/service/$rootScopeng/service/$sceng/service/$sceDelegateng/service/$templateCacheng/service/$timeoutng/service/$windowng/typeng/type/$cacheFactory.Cacheng/type/$compile.directive.Attributesng/type/$rootScope.Scopeng/type/angular.Moduleng/type/form.FormControllerng/type/ngModel.NgModelControllerngAnimatengAnimate/providerngAnimate/provider/$animateProviderngAnimate/servicengAnimate/service/$animatengCookiesngCookies/servicengCookies/service/$cookiesngCookies/service/$cookieStorengMessagesngMessages/directivengMessages/directive/ngMessagengMessages/directive/ngMessagesngMockngMock/functionngMock/function/angular.mock.dumpngMock/function/angular.mock.injectngMock/function/angular.mock.modulengMock/objectngMock/object/angular.mockngMock/providerngMock/provider/$exceptionHandlerProviderngMock/servicengMock/service/$exceptionHandlerngMock/service/$httpBackendngMock/service/$intervalngMock/service/$logngMock/service/$timeoutngMock/typengMock/type/angular.mock.TzDatengMockE2EngMockE2E/servicengMockE2E/service/$httpBackendngResourcengResource/servicengResource/service/$resourcengRoutengRoute/directivengRoute/directive/ngViewngRoute/providerngRoute/provider/$routeProviderngRoute/servicengRoute/service/$routengRoute/service/$routeParamsngSanitizengSanitize/filterngSanitize/filter/linkyngSanitize/servicengSanitize/service/$sanitizengTouchngTouch/directivengTouch/directive/ngClickngTouch/directive/ngSwipeLeftngTouch/directive/ngSwipeRightngTouch/servicengTouch/service/$swipe
文字

AngularJS: API: ng/type/$rootScope.Scope


$rootScope.Scope

  1. - 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.)

Here is a simple scope snippet to show how you can interact with the scope.

<file src="./test/ng/rootScopeSpec.js" tag="docs1" />

Inheritance

A scope can inherit from a parent scope, as in this example:

         var parent = $rootScope;
         var child = parent.$new();

         parent.salutation = "Hello";
         child.name= "World";
         expect(child.salutation).toEqual('Hello');

         child.salutation = "Welcome";
         expect(child.salutation).toEqual('Welcome');
         expect(parent.salutation).toEqual('Hello');

用法

$rootScope.Scope([providers], [instanceCache]);

参数

参数 类型 详述
providers
(可选)
Object.<string, function()>=

Map of service factory which need to be provided for the current scope. Defaults to ng.

instanceCache
(可选)
Object.<string, *>=

Provides pre-instantiated services which should append/override services provided by providers. This is handy when unit-testing and having the need to override a default service.

返回值

Object

Newly created scope.

方法

  • $new(isolate);

    Creates a new child scope.

    The parent scope will propagate the $digest() and $digest() events. 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.

    参数

    参数 类型 详述
    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.

    返回值

    Object

    The newly created child scope.

  • $watch(watchExpression, [listener], [objectEquality]);

    Registers a listener callback to be executed whenever the watchExpression changes.

    • The watchExpression is called on every call to $digest() and should return the value that will be watched. (Since $digest() reruns when it detects changes the watchExpression can execute multiple times per $digest() and should be idempotent.)
    • The listener is called only when the value from the current watchExpression and the previous call to watchExpression 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, unless objectEquality == true (see next point)
    • When objectEquality == true, inequality of the watchExpression is determined according to the angular.equals function. To save the value of the object for later comparison, the angular.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 other listeners 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 no listener. (Since watchExpression can execute multiple times per $digest cycle when a change is detected, be prepared for multiple calls to your listener.)

    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 of watchExpression didn't change. To detect this scenario within the listener fn, you can compare the newVal and oldVal. If these two values are identical (===) then the listener was called due to initialization.

    The example below contains an illustration of using a function as your $watch listener

    示例:

               // 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 listener function
               var food;
               scope.foodCounter = 0;
               expect(scope.foodCounter).toEqual(0);
               scope.$watch(
                 // This is the listener function
                 Function() { return food; },
                 // This is the change handler
                 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);

    参数

    参数 类型 详述
    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 current scope as a parameter.
    listener
    (可选)
    function()=

    Callback called whenever the return value of the watchExpression changes.

    • string: Evaluated as expression
    • Function(newValue, oldValue, scope): called with current and previous values as parameters.
    objectEquality
    (可选)
    boolean

    Compare for object equality using angular.equals instead of comparing for reference equality.

    返回值

    function()

    Returns a deregistration function for this listener.

  • $watchGroup(watchExpressions, listener);

    A variant of $watch() where it watches an array of watchExpressions. If any one expression in the collection changes the listener 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 the watchExpressions array changes.

    参数

    参数 类型 详述
    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 The newValues array contains the current values of the watchExpressions, with the indexes matching those of watchExpression and the oldValues array contains the previous values of the watchExpressions, with the indexes matching those of watchExpression The scope refers to the current scope.

    返回值

    function()

    Returns a de-registration function for all listeners.

  • $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 the obj 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);

    参数

    参数 类型 详述
    obj stringfunction(scope)

    Evaluated as expression. The expression value should evaluate to an object or an array which is observed on each $digest cycle. Any shallow change within the collection will trigger a call to the listener.

    listener function(newCollection, oldCollection, scope)

    a callback function called when a change is detected.

    • The newCollection object is the newly modified data obtained from the obj expression
    • The oldCollection object is a copy of the former collection data. Due to performance considerations, theoldCollection value is computed only if the listener function declares two or more arguments.
    • The scope argument refers to the current scope.

    返回值

    function()

    Returns a de-registration function for this listener. When the de-registration function is executed, the internal watch operation is terminated.

  • $digest();

    Processes all of the watchers of the current scope and its children. Because a watcher's listener can change the model, the $digest() keeps calling the watchers until no more listeners are firing. This means that it is possible to get into an infinite loop. This function will throw 'Maximum iteration limit exceeded.' if the number of iterations exceeds 10.

    Usually, you don't call $digest() directly in controllers or in directives. Instead, you should call $apply() (typically from within a Directive), which will force a $digest().

    If you want to be notified whenever $digest() is called, you can register a watchExpression function with $watch() with no listener.

    In unit tests, you may need to call $digest() to simulate the scope life cycle.

    示例:

               var scope = ...;
               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);
  • $destroy();

    Removes the current scope (and all of its children) from the parent scope. Removal implies that calls to $digest() will no longer propagate to the current scope and its children. Removal also implies that the current scope is eligible for garbage collection.

    The $destroy() is usually used by directives such as ngRepeat for managing the unrolling of the loop.

    Just before a scope is destroyed, a $destroy event is broadcasted on this scope. Application code can register a $destroy event handler that will give it a chance to perform any necessary cleanup.

    Note that, in AngularJS, there is also a $destroy jQuery event, which can be used to clean up DOM bindings before an element is removed from the DOM.

  • $eval([expression], [locals]);

    Executes the expression on the current scope and returns the result. Any exceptions in the expression are propagated (uncaught). This is useful when evaluating Angular表达式s.

    示例:

               var scope = ng.$rootScope.Scope();
               scope.a = 1;
               scope.b = 2;
    
               expect(scope.$eval('a+b')).toEqual(3);
               expect(scope.$eval(Function(scope){ return scope.a + scope.b; })).toEqual(3);

    参数

    参数 类型 详述
    expression
    (可选)
    stringfunction()

    An Angular表达式 to be executed.

    • string: execute using the rules as defined in expression.
    • Function(scope): execute the function with the current scope parameter.
    locals
    (可选)
    Object

    Local variables object, useful for overriding values in scope.

    返回值

    *

    The result of evaluating the expression.

  • $evalAsync([expression]);

    Executes the expression on the current scope at a later point in time.

    The $evalAsync makes no guarantees as to when the expression will be executed, only that:

    • it will execute after the function that scheduled the evaluation (preferably before DOM rendering).
    • at least one $digest cycle will be performed after expression execution.

    Any exceptions from the execution of the expression are forwarded to the $exceptionHandler service.

    注意: if this function is called outside of a $digest cycle, a new $digest cycle will be scheduled. However, it is encouraged to always call code that changes the model from within an $apply call. That includes code evaluated via $evalAsync.

    参数

    参数 类型 详述
    expression
    (可选)
    stringfunction()

    An Angular表达式 to be executed.

    • string: execute using the rules as defined in expression.
    • Function(scope): execute the function with the current scope parameter.
  • $apply([exp]);

    $apply() is used to execute an expression in angular from outside of the angular framework. (For example from browser DOM events, setTimeout, XHR or third party libraries). Because we are calling into the angular framework we need to perform proper scope life cycle of exception handling, executing watches.

    Life cycle

    Pseudo-Code of $apply()

               Function $apply(expr) {
                 try {
                   return $eval(expr);
                 } catch (e) {
                   $exceptionHandler(e);
                 } finally {
                   $root.$digest();
                 }
               }

    Scope's $apply() method transitions through the following stages:

    1. The expression is executed using the $eval() method.
    2. Any exceptions from the execution of the expression are forwarded to the $exceptionHandler service.
    3. The watch listeners are fired immediately after the expression was executed using the $digest() method.

    参数

    参数 类型 详述
    exp
    (可选)
    stringfunction()

    An Angular表达式 to be executed.

    • string: execute using the rules as defined in expression.
    • Function(scope): execute the function with current scope parameter.

    返回值

    *

    The result of evaluating the expression.

  • $on(名称, listener);

    Listens on events of a given type. See $emit for discussion of event life cycle.

    The event listener function format is: Function(event, args...). The event object passed into the listener has the following attributes:

    • targetScope - {Scope}: the scope on which the event was $emit-ed or $broadcast-ed.
    • currentScope - {Scope}: the scope that is currently handling the event. Once the event propagates through the scope hierarchy, this property is set to null.
    • 名称 - {string}: name of the event.
    • stopPropagation - {Function=}: calling stopPropagation function will cancel further event propagation (available only for events that were $emit-ed).
    • preventDefault - {Function}: calling preventDefault sets defaultPrevented flag to true.
    • defaultPrevented - {boolean}: true if preventDefault was called.

    参数

    参数 类型 详述
    name string

    Event name to listen on.

    listener function(event, ...args)

    Function to call when the event is emitted.

    返回值

    function()

    Returns a deregistration function for this listener.

  • $emit(名称, args);

    Dispatches an event 名称 upwards through the scope hierarchy notifying the registered $rootScope.Scope listeners.

    The event life cycle starts at the scope on which $emit was called. All listeners listening for 名称 event on this scope get notified. Afterwards, the event traverses upwards toward the root scope and calls all registered listeners along the way. The event will stop propagating if one of the listeners cancels it.

    Any exception emitted from the listeners will be passed onto the $exceptionHandler service.

    参数

    参数 类型 详述
    name string

    Event name to emit.

    args *

    Optional one or more arguments which will be passed onto the event listeners.

    返回值

    Object

    Event object (see $rootScope.Scope).

  • $broadcast(名称, args);

    Dispatches an event 名称 downwards to all child scopes (and their children) notifying the registered $rootScope.Scope listeners.

    The event life cycle starts at the scope on which $broadcast was called. All listeners listening for 名称 event on this scope get notified. Afterwards, the event propagates to all direct and indirect scopes of the current scope and calls all registered listeners along the way. The event cannot be canceled.

    Any exception emitted from the listeners will be passed onto the $exceptionHandler service.

    参数

    参数 类型 详述
    name string

    Event name to broadcast.

    args *

    Optional one or more arguments which will be passed onto the event listeners.

    返回值

    Object

    Event object, see $rootScope.Scope

事件

  • $destroy

    Broadcasted when a scope and its children are being destroyed.

    Note that, in AngularJS, there is also a $destroy jQuery event, which can be used to clean up DOM bindings before an element is removed from the DOM.

    类型:

    broadcast

    目标:

    scope being destroyed

属性

  • $id


上一篇:下一篇: