AngularJS - Controllers And Scopes
AngularJS ControllersThere is a logic behind AngularJS View and AngularJS Models .
The main aspect, which controls AngularJS are controllers itself. To define AngularJS controllers, we use a directive ng-controller.
Let's see its example.
ExplanationHere, ng-app defines AngularJS Application and name is given as "smApp". Ultimately, it has created a root scope of Application as well.. This AngularJS Application is within the scope of this <div> only.
$scope is an owner of the Application variables and functions. Controller creates two properties "firstName" and "lastName" with the help of $scope Application object.
ng-model AngularJS directive is binding HTML input fields with the controller properties "firstName" and "lastName".
One important Application object, which is available at all the three layers is Scope denoted by $Scope. We'll learn more about AngularJS Scope later.
Controller MethodsIn the last example of this article, we have seen that the Application properties (e.g. firstName and lastName) can be set inside controller but, how to define the methods in AngularJS Application.
Let's see an example, understand it's implementation and execution.
ExplanationIn this example, we can see a method fullName() is called in AngularJS Application, which is defined in controller part of an Application.
As we are using an Application object $Scope at the multiple locations, let's understand it as well.
If an Application is small, there is no issue to find out the scope which you are dealing with. If the Application is large, there are multiple scopes, where certain sections have access to the fixed set of available scopes.
Basically, there are two types of scopes in AngularJS Application, which are-
Root ScopeAll Applications have $rootScope. This scope is created on HTML element, which contains ng-app directive and is available for an entire Application.
Current ScopeThis $scope is created on HTML element, which contains ng-controller directive.
If root scope and current scope both have a property of the same name, the value of current scope will be used by the Application.
Let's understand it, using an example, given below.
ExplanationHere, the value of color property in controller part is Green, else it's Red throughout the Application due to the availability of $rootScope.