«

»

Apr 10

Scope in AngularJs

Scope is object in AngularJs that refers to the application model. The concept of scope in AngularJs is crucial. Scope is glue which allow to template, model and controller to work together.
scope uses along with information contained in the template, data model and controller, to keep model and view separate. but any change in model and view reflected to each other. scope is an execution context for expressions. Scopes can watch expressions and propagate events.

Scope as Data-Model

In Template linking phase the directive setup $watch expressions on the scope. The $watch allows the directive to be notified of property changes which allows the directive to render the update value to the DOM. Controllers and Directives have the reference to the scope. This is isolates controller from the directive as well as from DOM.

Example

JavaScript Code


angular.module('scopeExample', [])
.controller('MyController', ['$scope', function($scope) {
$scope.username = 'World';

$scope.sayHello = function() {
$scope.greeting = ‘Hello ‘ + $scope.username + ‘!’;
};
}]);

In Example mycontroller assign “world” to the “username” property of the scope.The scope then notifies the input of the assignment, which then renders the input with username pre-filled.

Logically the rendering of {{greeting}} involves:

1. Retrieval of the scope associated with DOM node where {{greeting}} is defined in template. In this example this is the same scope as the scope which was passed into MyController.

2. Evaluate the greeting expression against the scope retrieved above, and assign the result to the text of the enclosing DOM element.

For More Details Click Here

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>