Categories: AngularJs

Controllers – AngularJS

Controllers are used to control the flow of data in AngularJS application. ng-controller directive is used to define controller.

Controllers are JavaScript objects that contain attributes and functions. Attributes are also called as properties. $scope object is used to invoke the controller. $scope refers to the application which uses the application.

We are creating a simple Controller here:

[html]
{{ state + ” ” + city }}
Full Address: {{address}}

var app = angular.module("firstApp", []);

app.controller("firstCtroller", function($scope) { $scope.state = "Hyderabad"; $scope.city = "Sikandrabad"; $scope.address = $scope.state + " " + $scope.city; });


[/html]

In above example, firstApp as an application that is owner of the angularJS program.
We have defined controller named firstCtroller by using ng-controller directive.
It has a parameter $scope that refers to the application.

Example:2

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

[/html]

$scope.addr is property of controller firstCtroller object.

state and city are property of $scope.addr object.
address is the function of $scope.addr object whose returns the combined address.

Put Controller in separate external file:

We can put Controller in separate external file and can refer that file in HTML.

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

[/html]

File firstCtroller.js contains following code:

[html]

[/html]

jeff77

Disqus Comments Loading...

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