What are Scopes?
Scope is an object that refers to the application
model. It is an execution context for expressions. Scopes are
arranged in hierarchical structure which mimic the DOM structure of the application. Scopes can
watch expressions and propagate events.
Scope characteristics
- Scopes provide APIs ($watch) to observe
model mutations.
- Scopes provide APIs ($apply) to
propagate any model changes through the system into the view from outside of the "Angular
realm" (controllers, services, Angular event handlers).
- Scopes can be nested to limit access to the properties of application components while providing
access to shared model properties. Nested scopes are either "child scopes" or "isolate scopes".
A "child scope" (prototypically) inherits properties from its parent scope. An "isolate scope"
does not. See isolated
scopes for more information.
- Scopes provide context against which expressions are evaluated. For
example
{{username}}expression is meaningless, unless it is evaluated against a specific scope which defines theusernameproperty.
Scope as Data-Model
Scope is the glue between application controller and the view. During the template linking phase the directives set up$watchexpressions on the scope. The$watchallows the directives to be notified of property changes, which allows the directive to render the updated value to the DOM.Both controllers and directives have reference to the scope, but not to each other. This arrangement isolates the controller from the directive as well as from the DOM. This is an important point since it makes the controllers view agnostic, which greatly improves the testing story of the applications.angular.module('scopeExample', []) .controller('MyController', ['$scope', function($scope) { $scope.username = 'World'; $scope.sayHello = function() { $scope.greeting = 'Hello ' + $scope.username + '!'; }; }]);
No comments:
Post a Comment