بلاگ

12 آڪٽوبر 2018

AngularJS Controller

What is the role of Controller in AngularJS?

Data flow in the application is maintained by controllers in AngularJS. In general terms, AngularJS Controller is a JavaScript object which is basically used to maintain the flow of data in the angular application.

To make a controller we will use ng-controller directive.

Let us understand by a simple example:-

مثال طور:

<div ng-app=”myModule” ng-controller=”myController”>

First Name: <input type=”text” ng-model=”firstName”><br>
Last Name: <input type=”text” ng-model=”lastName”><br>
<br>
Full Name: {{firstName + ” ” + lastName}}

</ div>

<لپي>
var app = angular.module(‘myModule’, []);
app.controller(‘myController’, function($scope) {
$scope.firstName = “Simba”;
$scope.lastName = “Singh”;
})؛
</ اسڪرپٽ>

Output: – Simba Singh

In this example controller object has two properties. First one is firstName and second is lastOne.

Controller with methods

Controllers not only hold properties but also hold methods. In the below example we should make a function called “loginInfo” which will used to return login details.

مثال طور:

<div ng-app=”myModule” ng-controller=”myController”>

EmailId: <input type=”text” ng-model=”email”><br>
Password: <input type=”text” ng-model=”pwd”><br>
<br>
Full Name: {{ loginInfo ()}}

</ div>

<لپي>
var app = angular.module(‘myModule’, []);
app.controller(‘myController’, function($scope) {
$scope.email = “its@gmail.com”;
$scope.pwd = “admin”;
$scope.loginInfo = function() {
return $scope.email + ” ” + $scope.pwd;
};
})؛
</ اسڪرپٽ>

Output: – its@gmail.com admin

Controller in external file

In large scale project we could define controller in external file. These procedures increase a great scalability and reliability in angular application.

To accomplish this we need two files:-

  • First, index.html file
  • Second, Controller.js file

So, first create index.html file.

مثال طور:

<div ng-app=”myModule” ng-controller=”myController.js”>

Email: <input type=”text” ng-model=”email”><br>
Password: <input type=”text” ng-model=”pwd”><br>
<br>
Full Name: {{ loginDetails ()}}

</ div>

<script src=”Controller.js”></script>

Then write the following code in Controller.js…….

مثال طور:

var app = angular.module (‘myModule’, []);
app.controller (‘myController’, function($scope) {
$scope.email = “its@gmail.com”;
$scope.pwd = “admin”;
$scope.loginInfo = function() {
return $scope.email + ” ” + $scope.pwd;
};
})؛

Angular JS Training

In Just 4 Days
هاڻي وڌو

GTranslate Your license is inactive or expired, please subscribe again!