Categories: AngularJs

Scope – AngularJS

Scope joins the view and the controller.

There are 3 parts of AngularJS program: Model, View and Controller.

$scope is JavaScript Object that contains Model data(properties and methods) and is accessible to view and controller.
$scope is passed as argument in controller. It should be first argument.

Functions can also be defined in $scope object.

[html]
Enter state name:
Enter city name:
Address name:
Address name: {{addr.address()}}


[/html]

Scope Inheritance:

We can define nested controllers. Scopes are defined controller specific. So if nested controllers are defined then child controllers will inherit parent controller’s scope.

Understand with given example:

[html]
{{message}} – {{type}}
{{message}} – {{type}}
{{message}} – {{type}}

firstApp.controller("firstCtroller", function($scope) { $scope.message = "In First controller"; $scope.type = "Type 1"; });

firstApp.controller("secondController", function($scope) { $scope.message = "In Second controller"; });

firstApp.controller("thirdController", function($scope) { $scope.message = "In third controller"; $scope.type = "Type 3"; });


[/html]

Root scope: $rootScope is created on the HTML element which contains ng-app directive. It is globally available to entire application.

[html]
Enter state name:
Enter city name:
Address name:
Enter state name local ctrl:
Enter city name local ctrl:
Address name local ctrl:

app.run(function($rootScope) { $rootScope.addr = { state: "Delhi", city: "GZB", address: function(){ var empObject; empObject = $rootScope.addr; return empObject.state + " " + empObject.city; } }; });

app.controller('firstCtroller', function($scope) { $scope.addr = { state: "Hyderabad", city: "Sikandrabad", address: function(){ var empObject; empObject = $scope.addr; return empObject.state + " " + empObject.city; } }; });


[/html]

jeff77

Disqus Comments Loading...
Share
Published by
jeff77

Recent Posts

Noun

A Noun is the name of a person, place or thing. or Name of anything is noun. For example: Sita…

10 years ago

Introduction – AngularJS

Misko Hevery, a Google employee, developed AngularJS. First version 1.0 of AngularJS was released in 2012. Now AngularJS is fully…

9 years ago

Expressions – AngularJS

AngularJS expressions contain operators,literals, and variables.  AngularJS expressions can be written inside HTML while JavaScript expressions can't be.  AngularJS expressions…

9 years ago

Noun – Exercise

Some sentences are given below. Choose the nouns and mention the type of noun whether they are proper noun, common…

9 years ago

Modules – AngularJS

Modules are containers for appication controller. They contain different parts of an application. [html] {{ state + " " +…

9 years ago

Directives – AngularJS

Using Directives you can extend HTML attributes. In AngularJS you can define your own directives while it has its own…

9 years ago