Saturday, January 9, 2016

AngularJS – Scopes

The $scope object is where we create the business functionality of the application, methods in our controllers, and properties in the views. Scopes serve as the glue between the controller and the view.
Scopes provide the ability to watch for the model changes. They give the developer the ability to propagate the model changes throughout the application by using the apply mechanism available on the scope.

It is ideal to contain the application logic in controller and model working data on the scope of the controller.

When Angular starts to run and generates the view, it will create a binding from the root ng-app element to the $rootScope. This scope is the eventually parent of all the $scope objects. The $rootScope object is the closest object we have to the global context in the Angular app. It’s a bad idea to attach too much logic to this global context, in the similar way that it’s not a good idea to dirty the JavaScript global scope.

Scopes have the following basic functions:
  •          They provide observers to watch for model changes.
  •         They provide the ability to propagate model changes through the applications as well as outside the systems to other components.
  •         They can be nested such that they can isolate functionality and model properties.
  •         They provide an execution environment in which expressions are evaluated.

    Example



Output

In the above example notice that the Mycontroller assigns the value “Jatin” to the username property on the scope. The Scope then notifies the input of the assignment, which then renders the input with the username pre-filled. This demonstrates how controller can write data to the scope.

Similarly the controller can assign behavior to the scope as seen by the sayHello method, which is involved when the user clicks on the ‘greet’ button. The sayHello method reads the username property and creates the greeting property. This demonstrates that the properties on scope update automatically when they are bound to the HTML input widgets.

 


No comments:

Post a Comment